Dates & Times
Programs constantly deal with dates and times: due dates, birthdays, opening hours, transaction timestamps. Python's datetime module lets you create, format, parse, compare and do arithmetic with them reliably.
The main types
| Type | Stores | Example |
|---|---|---|
date | Year, month, day | date(2026, 3, 14) |
time | Hour, minute, second, microsecond | time(9, 30) |
datetime | A date and a time together | datetime(2026, 3, 14, 9, 30) |
timedelta | A length of time (duration) | timedelta(days=7) |
timezone / zoneinfo.ZoneInfo | Time zone information | ZoneInfo("Africa/Nairobi") |
Creating dates and datetimes
from datetime import date, datetime exam_day = date(2026, 3, 14) print(exam_day) print(exam_day.year, exam_day.month, exam_day.day) print(exam_day.weekday()) # Monday is 0, Sunday is 6 start = datetime(2026, 3, 14, 9, 30) print(start) print(start.date(), start.hour, start.minute)
To get the current date and time, use date.today() and datetime.now(). Their output depends on when you run them, so this is just an example:
from datetime import date, datetime print(date.today()) print(datetime.now())
Formatting with strftime
strftime() ("string format time") turns a date into text in any layout you choose, using format codes:
| Code | Meaning | Example |
|---|---|---|
%d | Day of month, two digits | 14 |
%m | Month number, two digits | 03 |
%Y / %y | Year with century / without | 2026 / 26 |
%B / %b | Month name, full / short | March / Mar |
%A / %a | Weekday name, full / short | Saturday / Sat |
%H / %I | Hour, 24-hour / 12-hour clock | 09 |
%M / %S | Minutes / seconds | 30 / 00 |
%p | AM or PM | AM |
from datetime import datetime
start = datetime(2026, 3, 14, 9, 30)
print(start.strftime("%d/%m/%Y %H:%M"))
print(start.strftime("%A, %d %B %Y"))
print(start.strftime("%I:%M %p"))
print(f"Exam: {start:%a %d %b at %H:%M}") # format codes work in f-strings too
Month and day names follow your computer's language settings; on most systems they appear in English as shown.
Parsing text with strptime
datetime.strptime() ("string parse time") does the reverse: it reads text in a known format and builds a datetime. The format string must match the text exactly.
from datetime import datetime
party = datetime.strptime("25/12/2026 18:45", "%d/%m/%Y %H:%M")
print(party)
print(party.strftime("%A"))
stamp = datetime.fromisoformat("2026-03-14T09:30:00") # ISO 8601 text
print(stamp.isoformat())
If the text doesn't match the format, strptime raises a ValueError, which you can handle with try/except.
Date arithmetic with timedelta
Add or subtract a timedelta to move dates forward or back. Subtracting two dates gives a timedelta.
from datetime import date, datetime, timedelta today = date(2026, 3, 14) print(today + timedelta(days=30)) # a loan due in 30 days print(today - timedelta(weeks=2)) holiday = date(2026, 12, 25) gap = holiday - today print(gap) print(gap.days, "days until Christmas") shift_start = datetime(2026, 3, 14, 8, 30) shift_end = datetime(2026, 3, 14, 17, 15) worked = shift_end - shift_start print(worked) print(worked.total_seconds() / 3600, "hours")
Dates compare naturally, so you can use <, > and ==, and loop over a range of days:
from datetime import date, timedelta
start = date(2026, 3, 14)
for i in range(3):
day = start + timedelta(days=i)
print(day.strftime("%a %d %b"))
deadline = date(2026, 3, 20)
print(start < deadline)
A common real task is calculating someone's age. Comparing (month, day) tuples tells you whether this year's birthday has happened yet:
from datetime import date
def age_on(birthday, on_date):
had_birthday = (on_date.month, on_date.day) >= (birthday.month, birthday.day)
return on_date.year - birthday.year - (0 if had_birthday else 1)
print(age_on(date(2004, 8, 20), date(2026, 3, 14)))
print(age_on(date(2004, 8, 20), date(2026, 8, 20)))
timedelta works in days, seconds and microseconds; it has no "months" option because months have different lengths. To add calendar months, change the month value yourself (watching for year changes and short months) or use a third-party package such as python-dateutil.
Time zones
A datetime without time zone information is called naive; one with it is aware. For anything involving users in different countries, store aware datetimes. The zoneinfo module provides real time zones by name.
from datetime import datetime
from zoneinfo import ZoneInfo
meeting = datetime(2026, 3, 14, 9, 30, tzinfo=ZoneInfo("Africa/Nairobi"))
print(meeting)
print(meeting.astimezone(ZoneInfo("Europe/London")))
print(meeting.astimezone(ZoneInfo("Africa/Lagos")))
East Africa Time is three hours ahead of UTC all year round. London switches to summer time later in March, so the gap would shrink to two hours after that.
On Windows, ZoneInfo("Africa/Nairobi") can fail with ZoneInfoNotFoundError because Windows doesn't include the time zone database Python needs. Install it with python -m pip install tzdata (see pip & virtual environments).
datetime.utcnow() is deprecated since Python 3.12 because it returns a naive datetime that is easy to misread. Use datetime.now(timezone.utc) (with from datetime import timezone) to get the current UTC time as an aware datetime. Also, don't compare naive and aware datetimes: Python raises a TypeError.
When saving dates to files or sending them to APIs, use the ISO 8601 format with isoformat(), and read them back with fromisoformat(). ISO dates such as 2026-03-14 also sort correctly as plain text.
Key points
- Use
date,time,datetimeandtimedeltafrom thedatetimemodule. strftimeformats dates as text;strptimeparses text into dates.- Add a
timedeltato move dates; subtract dates to get a duration. - Use
zoneinfo.ZoneInfofor time zones, and avoid the deprecatedutcnow().
Tip: use the ← and → keys to move between pages.
