The datetime module — from the standard library, per the Modules and Imports lesson — is Python's tool for working with dates and times.
from datetime import datetime
now = datetime.now()
print(now) # 2026-07-30 14:30:00.123456
print(now.strftime("%Y-%m-%d")) # "2026-07-30"
print(now.strftime("%d/%m/%Y")) # "30/07/2026"
print(now.strftime("%A, %B %d, %Y"))# "Thursday, July 30, 2026"| Code | Means |
|---|---|
| %Y | 4-digit year |
| %m | 2-digit month |
| %d | 2-digit day |
| %H:%M:%S | Hour:minute:second, 24-hour |
| %A | Full day name |
| %B | Full month name |
The full set of format codes is in the strftime() reference on python.org.
from datetime import datetime
deadline = datetime(2026, 12, 31)
print(deadline.strftime("%Y-%m-%d")) # "2026-12-31"from datetime import datetime, timedelta
now = datetime.now()
deadline = datetime(2026, 12, 31)
difference = deadline - now
print(f"{difference.days} days remaining")
next_week = now + timedelta(days=7)
print(next_week.strftime("%Y-%m-%d"))timedelta represents a span of time, and can be added to or subtracted from a datetime directly — no separate "modify" method needed.
strptime() is the reverse of strftime() — it reads a date out of a string, using the same format codes to say what shape to expect:
from datetime import datetime
text = "30/07/2026"
parsed = datetime.strptime(text, "%d/%m/%Y")
print(parsed.year) # 2026
print(parsed.month) # 7strptime() does not guess the format
The format string must match the input exactly, or strptime() raises a ValueError — "30/07/2026" parsed with "%Y-%m-%d" fails outright rather than guessing. Wrap this in try/except whenever the text is coming from a user rather than a source you fully control.
No time zone by default
Dates and times in Python default to "naive" — no time zone attached at all, rather than automatically using the server's configured zone. For anything where the difference matters (a scheduled event across regions), look at the zoneinfo module in the standard library.