Python Datetime
Work with dates and times using datetime, strftime, strptime, and timedelta.
The datetime Module
Python's datetime module provides classes for working with dates and times.
The main ones: datetime (date + time combined), date (date only),
time (time only), and timedelta (a duration). They are all in the standard
library — no installation needed.
Getting the Current Date and Time
from datetime import datetime, date now = datetime.now() print(now) print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}") print(f"Time: {now.hour}:{now.minute:02d}:{now.second:02d}") print(date.today())
2024-01-15 14:32:07.123456 Year: 2024, Month: 1, Day: 15 Time: 14:32:07 2024-01-15
Formatting with strftime()
strftime() converts a datetime to a formatted string. The format codes start with
%: %Y = 4-digit year, %m = month number, %d = day,
%B = full month name, %A = weekday name, %H = hour (24h),
%I = hour (12h), %p = AM/PM.
from datetime import datetime now = datetime.now() print(now.strftime("%d/%m/%Y")) print(now.strftime("%B %d, %Y")) print(now.strftime("%I:%M %p")) print(now.strftime("%A, %d %B %Y"))
15/01/2024 January 15, 2024 02:32 PM Monday, 15 January 2024
Parsing with strptime()
strptime() parses a date string into a datetime object. You must supply the exact
format that matches the string. Essential when reading dates from user input or files.
from datetime import datetime dt = datetime.strptime("25/12/2024", "%d/%m/%Y") print(dt) print(dt.strftime("%A")) # what day of the week?
2024-12-25 00:00:00 Wednesday
Date Arithmetic with timedelta
A timedelta represents a duration. Add or subtract from dates to get future or past
dates — useful for deadlines, expiry times, and scheduling.
from datetime import datetime, timedelta now = datetime.now() print((now + timedelta(days=30)).strftime("%d %b %Y")) print((now - timedelta(weeks=2)).strftime("%d %b %Y")) d1 = datetime(2024, 1, 1) d2 = datetime(2024, 12, 31) print(f"Days in 2024: {(d2-d1).days}")
14 Feb 2024 01 Jan 2024 Days in 2024: 365
zoneinfo (Python 3.9+) or the third-party pytz library. Naive datetime objects can cause subtle bugs in production.🧠 Quick Check
Which method formats a datetime as a string?