How to Work with Dates in Python
Learn how to create, format, and manipulate dates and times in Python using the datetime module.
Python’s datetime module provides classes for working with dates and times. Here’s how to use them effectively.
Importing datetime
from datetime import datetime, date, time, timedelta
Getting Current Date and Time
from datetime import datetime, date
# Current date and time
now = datetime.now()
print(now) # 2026-02-02 14:30:45.123456
# Current date only
today = date.today()
print(today) # 2026-02-02
# Current time only
current_time = datetime.now().time()
print(current_time) # 14:30:45.123456
Creating Dates and Times
from datetime import datetime, date, time
# Create a specific date
my_date = date(2026, 12, 25)
print(my_date) # 2026-12-25
# Create a specific datetime
my_datetime = datetime(2026, 12, 25, 10, 30, 0)
print(my_datetime) # 2026-12-25 10:30:00
# Create a specific time
my_time = time(14, 30, 45)
print(my_time) # 14:30:45
Accessing Date/Time Components
from datetime import datetime
now = datetime.now()
print(now.year) # 2026
print(now.month) # 2
print(now.day) # 2
print(now.hour) # 14
print(now.minute) # 30
print(now.second) # 45
print(now.weekday()) # 0 (Monday=0, Sunday=6)
Formatting Dates (strftime)
Convert datetime to string:
from datetime import datetime
now = datetime.now()
# Common formats
print(now.strftime("%Y-%m-%d")) # 2026-02-02
print(now.strftime("%d/%m/%Y")) # 02/02/2026
print(now.strftime("%B %d, %Y")) # February 02, 2026
print(now.strftime("%H:%M:%S")) # 14:30:45
print(now.strftime("%I:%M %p")) # 02:30 PM
print(now.strftime("%A, %B %d, %Y")) # Monday, February 02, 2026
Common Format Codes
| Code | Meaning | Example |
|---|---|---|
| %Y | Year (4 digits) | 2026 |
| %m | Month (01-12) | 02 |
| %d | Day (01-31) | 02 |
| %H | Hour (00-23) | 14 |
| %I | Hour (01-12) | 02 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 45 |
| %p | AM/PM | PM |
| %A | Weekday name | Monday |
| %B | Month name | February |
Parsing Dates (strptime)
Convert string to datetime:
from datetime import datetime
# Parse various formats
date1 = datetime.strptime("2026-02-02", "%Y-%m-%d")
date2 = datetime.strptime("02/02/2026", "%d/%m/%Y")
date3 = datetime.strptime("February 02, 2026", "%B %d, %Y")
print(date1) # 2026-02-02 00:00:00
Date Arithmetic with timedelta
from datetime import datetime, timedelta
now = datetime.now()
# Add/subtract time
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
two_hours_ago = now - timedelta(hours=2)
in_30_minutes = now + timedelta(minutes=30)
print(tomorrow) # 2026-02-03 14:30:45
print(next_week) # 2026-02-09 14:30:45
# Calculate difference between dates
date1 = datetime(2026, 3, 1)
date2 = datetime(2026, 2, 1)
difference = date1 - date2
print(difference.days) # 28
Comparing Dates
from datetime import datetime
date1 = datetime(2026, 1, 1)
date2 = datetime(2026, 12, 31)
print(date1 < date2) # True
print(date1 > date2) # False
print(date1 == date2) # False
# Check if date is in the past
now = datetime.now()
past_date = datetime(2020, 1, 1)
print(past_date < now) # True
Working with Timezones
from datetime import datetime, timezone, timedelta
# UTC time
utc_now = datetime.now(timezone.utc)
print(utc_now) # 2026-02-02 12:30:45+00:00
# Create timezone offset
est = timezone(timedelta(hours=-5))
est_time = datetime.now(est)
print(est_time) # 2026-02-02 07:30:45-05:00
# Convert between timezones
utc_time = datetime.now(timezone.utc)
est_time = utc_time.astimezone(timezone(timedelta(hours=-5)))
Practical Examples
from datetime import datetime, timedelta
# Calculate age
def calculate_age(birthdate):
today = date.today()
age = today.year - birthdate.year
if (today.month, today.day) < (birthdate.month, birthdate.day):
age -= 1
return age
birth = date(1990, 6, 15)
print(f"Age: {calculate_age(birth)}")
# Check if date is a weekend
def is_weekend(dt):
return dt.weekday() >= 5 # Saturday=5, Sunday=6
print(is_weekend(datetime.now()))
# Get start and end of current month
def month_range():
today = date.today()
start = today.replace(day=1)
next_month = today.replace(day=28) + timedelta(days=4)
end = next_month - timedelta(days=next_month.day)
return start, end
start, end = month_range()
print(f"Month: {start} to {end}")
Summary
- Use
datetime.now()for current date/time - Use
strftime()to format dates as strings - Use
strptime()to parse strings into dates - Use
timedeltafor date arithmetic - Compare dates with
<,>,==operators - Use
timezonefor timezone-aware datetimes