L5·Intermediate/Advanced

📅Dates, Times & Time Zones

datetime, timedelta, strftime/strptime and zoneinfo.

datetimetimedeltazoneinfostrftime

§ 1Core types

date (day), time (clock), datetime (both), timedelta (a duration). Subtracting datetimes gives a timedelta.

§ 2Format & parse

strftime turns a datetime into text, strptime parses text. %Y year, %m month, %d day, %H hour, %M minute.

1from datetime import datetime​
2d = datetime.strptime("27-10-2026", "%d-%m-%Y")​
3print(d.strftime("%A, %d %b %Y"))​

§ 3Time zones

Naive datetimes have no zone — avoid them for real systems. Use zoneinfo.ZoneInfo('Asia/Kolkata') and store UTC.

Worked example

1from datetime import datetime, timedelta, timezone​
2from zoneinfo import ZoneInfo​
3​
4now = datetime(2026, 10, 27, 15, 30, tzinfo=timezone.utc)​
5print(now.astimezone(ZoneInfo("Asia/Kolkata")))​
6deadline = now + timedelta(days=7)​
7print((deadline - now).days, "days left")​
8print(deadline.isoformat())​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
datetime - datetime returns:

Lesson test

Take an 8-question test on “Dates, Times & Time Zones” — concepts, output prediction, bug spotting and interview questions.