datetime is Python’s standard module for working with dates and times. It’s part of the standard library — no installation needed.
Import
from datetime import datetime, date, timedelta
Current Date and Time
from datetime import datetime
now = datetime.now()
print(now) # 2025-05-07 14:32:15.123456
print(now.year) # 2025
print(now.month) # 5
print(now.day) # 7
print(now.hour) # 14
Formatting — strftime()
strftime() converts a datetime object to a string using a format template:
from datetime import datetime
now = datetime.now()
print(now.strftime('%d.%m.%Y')) # 07.05.2025
print(now.strftime('%d.%m')) # 07.05
print(now.strftime('%H:%M')) # 14:32
print(now.strftime('%d.%m.%Y %H:%M')) # 07.05.2025 14:32
Format codes:
| Code | Meaning | Example |
|---|---|---|
%d |
Day | 07 |
%m |
Month | 05 |
%Y |
Year (4 digits) | 2025 |
%H |
Hour (24h) | 14 |
%M |
Minutes | 32 |
Parsing a String — strptime()
The reverse operation: string → datetime:
from datetime import datetime
dt = datetime.strptime('2025-05-07', '%Y-%m-%d')
print(dt.year) # 2025
print(dt.month) # 5
Unix Timestamp — fromtimestamp()
A Unix timestamp is the number of seconds since January 1, 1970. Many APIs return time in this format (e.g., the dt field in OpenWeatherMap).
from datetime import datetime
timestamp = 1735689600 # number from an API
dt = datetime.fromtimestamp(timestamp)
print(dt) # 2025-01-01 00:00:00
print(dt.strftime('%d.%m.%Y')) # 01.01.2025
print(dt.strftime('%d.%m')) # 01.01
fromtimestamp() automatically accounts for your system’s timezone.
Comparing Dates
from datetime import date
today = date.today()
some_day = date(2025, 1, 1)
print(today > some_day) # True
diff = today - some_day
print(diff.days) # number of days between the dates
timedelta — Shifting Dates
from datetime import date, timedelta
today = date.today()
tomorrow = today + timedelta(days=1)
week_later = today + timedelta(days=7)
print(tomorrow) # tomorrow's date
print(week_later) # date one week from now
Practical Example: Filtering by Date
from datetime import datetime
items = [
{'dt': 1735689600, 'temp': -3},
{'dt': 1735776000, 'temp': -1},
{'dt': 1735862400, 'temp': 2},
]
seen_dates = set()
for item in items:
dt = datetime.fromtimestamp(item['dt'])
date_str = dt.strftime('%d.%m')
if date_str in seen_dates:
continue
seen_dates.add(date_str)
print(f"{date_str}: {item['temp']}°C")
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!