Python — Dates
The datetime module
from datetime import datetime, date, time, timedelta
now = datetime.now() # 2026-08-23 21:14:07.123456
today = date.today() # 2026-08-23
noon = time(12, 0) # 12:00:00
Building specific moments
launch = datetime(2026, 12, 31, 23, 59)
launch.year # 2026
launch.month # 12
launch.hour # 23
Argument order is fixed: (year, month, day[, hour, minute, second]) — no zero-month trap like JavaScript.
Formatting — strftime
now.strftime("%Y-%m-%d") # "2026-08-23"
now.strftime("%d/%m/%Y %H:%M") # "23/08/2026 21:14"
now.strftime("%A, %B %d") # "Sunday, August 23"
# locale-friendly:
now.strftime("%x %X")
| Code | Meaning |
|---|---|
%Y / %y | 4-digit / 2-digit year |
%m / %d | month / day (zero-padded) |
%H:%M:%S | 24h time |
%A / %B | weekday / month names |
Parsing strings → datetime — strptime
datetime.strptime("23/08/2026", "%d/%m/%Y")
# datetime(2026, 8, 23, 0, 0)
Format string MUST match the input exactly or ValueError. (f = format out, p = parse in.)
Math with timedelta
later = now + timedelta(days=30, hours=2)
ago = now - timedelta(weeks=1)
diff = later - now
diff.days # 30
diff.total_seconds()
Date arithmetic "just works" across month/year boundaries.
Comparisons
deadline = datetime(2026, 9, 1)
now < deadline # True — plain comparison operators
Timezones — the honest warning
Naive datetimes (no zone info) cause real production bugs:
from datetime import timezone
aware = datetime.now(timezone.utc) # UTC-aware ✓
aware.tzinfo # not None
local = aware.astimezone() # convert to local zone
Rule: store UTC, convert at display. For serious zone work use the zoneinfo module (stdlib) or pytz.
Timestamps
now.timestamp() # float seconds since epoch
datetime.fromtimestamp(1790000000)
Handy for measuring elapsed time; time.perf_counter() is better for pure durations.
Mini Practice
- Print today as YYYY-MM-DD and "Sunday, August 23" forms.
- Days until New Year via subtraction.
- Parse three user-entered date formats with strptime.
- Add 90 days to today; print weekday name.
- Build a naive vs aware UTC datetime pair; compare printing.
Next: math → (Python flavor)
Related Topics
Frequently Asked Questions about Dates
What is Dates in Python?
Dates is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Dates?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Dates.
Why is Dates important in Python?
Dates is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.