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 — there's no separate "modify" method the way PHP's DateTime::modify() works.
No time zone by default
Just like PHP, 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.