Dates and Times
Handling dates and times is one of the most common tasks in programming — recording log timestamps, calculating borrowing days, aggregating data over time periods... The
datetimemodule is Python's standard way of working with dates and times.
1. Getting the Current Time
from datetime import datetime, date, time
# Current datetime
now = datetime.now()
print(now) # 2026-06-23 16:00:00.123456
# Current date
today = date.today()
print(today) # 2026-06-23
# Create a specific date
d = datetime(2026, 6, 23, 15, 30, 0)
print(d) # 2026-06-23 15:30:00
Example: Birthday Reminder (Difficulty: Star)
from datetime import datetime
def days_to_birthday(birth_str):
"""Calculate days until next birthday"""
today = datetime.now()
birth = datetime.strptime(birth_str, "%m-%d")
birthday_this_year = birth.replace(year=today.year)
if birthday_this_year < today:
birthday_this_year = birthday_this_year.replace(year=today.year + 1)
delta = birthday_this_year - today
return delta.days
print(f"Days until next birthday: {days_to_birthday('12-25')}")
2. Formatting and Parsing
from datetime import datetime
# Date -> string (formatting)
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2026-06-23
print(now.strftime("%Y-%m-%d")) # 2026-06-23
print(now.strftime("%H:%M:%S")) # 16:00:00
print(now.strftime("%A")) # Tuesday
# String -> date (parsing)
date_str = "2026-06-23 15:30:00"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed) # 2026-06-23 15:30:00
| Format Code | Meaning | Example |
|---|---|---|
%Y |
4-digit year | 2026 |
%m |
2-digit month | 06 |
%d |
2-digit day | 23 |
%H |
Hour (24-hour) | 15 |
%M |
Minute | 30 |
%S |
Second | 00 |
%A |
Full weekday name | Tuesday |
Tip:
strftimeis "date -> string",strptimeis "string -> date". Remember: "f" = format (output), "p" = parse (input).
3. timedelta: Time Differences
from datetime import datetime, timedelta
now = datetime.now()
# Calculate future/past times
future = now + timedelta(days=7)
past = now - timedelta(days=30)
print(f"In 7 days: {future.strftime('%Y-%m-%d')}")
print(f"30 days ago: {past.strftime('%Y-%m-%d')}")
# Time calculation
print(timedelta(days=7)) # 7 days, 0:00:00
print(timedelta(hours=3, minutes=15)) # 3:15:00
print(timedelta(weeks=2)) # 14 days, 0:00:00
# Subtract two dates
d1 = datetime(2026, 6, 1)
d2 = datetime(2026, 6, 23)
diff = d2 - d1
print(f"Difference: {diff.days} days") # Difference: 22 days
Example: Subscription Expiry Reminder (Difficulty: Star-Star)
from datetime import datetime, timedelta
# Simulate user subscription info
subscriptions = [
{"name": "Zhang San", "expire": "2026-07-15"},
{"name": "Li Si", "expire": "2026-06-25"},
{"name": "Wang Wu", "expire": "2026-08-01"},
{"name": "Zhao Liu", "expire": "2026-06-20"},
]
today = datetime.now().strftime("%Y-%m-%d")
today = datetime.strptime(today, "%Y-%m-%d")
print("=== Subscription Expiry Check ===")
for sub in subscriptions:
expire = datetime.strptime(sub["expire"], "%Y-%m-%d")
remaining = (expire - today).days
if remaining < 0:
print(f"Expired ({sub['name']}): {-remaining} days ago")
elif remaining <= 7:
print(f"Expiring soon ({sub['name']}): {remaining} days left")
else:
print(f"Active ({sub['name']}): {remaining} days left")
Common Use Cases
- Log timestamps: Record the current time for each log entry.
- Expiry checking: Determine if a membership/subscription has expired.
- Date calculation: Compute the number of days between two dates.
- Time formatting: Display times in user-friendly formats.
- Scheduled tasks: Execute an operation at a specified time.
FAQ
datetime.now() return local time or UTC time?datetime.utcnow() for UTC. Note that utcnow() returns a naive datetime without timezone info. For production, use datetime.now(timezone.utc) or pytz/zoneinfo for proper timezone handling.strptime parsing fails?ValueError — "time data 'xxx' does not match format '%Y-%m-%d'". Wrap it in try-except to handle errors. Common pitfall: months and days must be two digits (%m won't match "6", it needs "06").timedelta?timedelta(days=1000000) is valid. However, total_seconds() might overflow. For everyday use, range is not a concern.Summary
datetime.now()gets current datetime;date.today()gets just the datestrftime()date -> string;strptime()string -> date- Common formats:
%Yyear,%mmonth,%dday,%Hhour,%Mminute,%Ssecond timedeltafor date arithmetic:days,hours,minutes,weeks- Subtracting two
datetimeobjects gives atimedelta;.daysproperty gets the difference in days
Exercises
-
Beginner (Difficulty: Star): Output the current time in these formats:
2026-06-23 Tuesday,2026-06-23 16:00,06/23/2026. -
Intermediate (Difficulty: Star-Star): Write a function
workdays_between(start, end)that calculates how many weekdays (Monday to Friday) there are between two dates. Hint: Usetimedeltato iterate each day; useweekday()to check the day of the week (0=Monday, 4=Friday). -
Advanced (Difficulty: Star-Star-Star): Write a "Pomodoro Timer." Work 25 minutes -> rest 5 minutes, loop 4 times, then take a long rest of 15 minutes. Use
time.sleep()for timing anddatetimeto display the current phase and remaining time.



