Dates & Time
- Create and format dates with
datetime - Parse strings into date objects with
strptime - Add and subtract time with
timedelta - Handle timezones properly with
zoneinfo
Naive datetime objects (no tzinfo) are the root cause of daylight-saving bugs and off-by-one-day reports in every analytics stack. Since Python 3.9, zoneinfo replaces pytz; datetime.now(tz=...) should always be timezone-aware in production.
- Comparing naive and aware datetimes — raises
TypeError; standardize on UTC-aware at boundaries. - Using
datetime.utcnow()— returns naive; preferdatetime.now(timezone.utc)for explicit UTC. - Doing calendar math with
timedelta(days=30)for "one month" — usedateutil.relativedeltafor real months.
Three types
date— year/month/daytime— hour/min/secdatetime— both
Arithmetic with timedelta
datetime + timedelta(days=N, hours=H) works as you'd expect.
strftime / strptime
dt.strftime("%Y-%m-%d")— format a datetime → stringdatetime.strptime(s, "%Y-%m-%d")— parse a string → datetime
Format codes: %Y year · %m month · %d day · %H:%M:%S time.
Try it
- How many days until your next birthday?
- Parse
"28/06/2026"(DD/MM/YYYY).
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Parse the string
"2026-07-13"into adateobject usingdatetime.strptime(ordate.fromisoformat). Print exactly the parsed date — output should include2026-07-13. - Exercise 2
Given
start = date(2026, 1, 1)andend = date(2026, 7, 13), compute the number of days between them and print just that number. Expected:193. - Exercise 3
Given
d = date(2026, 7, 13), add 30 days withtimedelta, then format the result as"DD/MM/YYYY"(usingstrftime). Expected:12/08/2026.