Skip to main content Brad's PyNotes

DateTime Module: Mastering Time and Dates in Python

TL;DR

The datetime module provides classes for manipulating dates and times, including datetime, date, time, and timedelta objects with timezone support and flexible formatting options.

Interesting!

Python’s datetime module automatically handles leap years, leap seconds, and complex calendar calculations - it knows that February 29, 2024 exists but February 29, 2023 doesn’t.

Core Classes and Operations

python code snippet start

from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
today = date.today()

# Date arithmetic
tomorrow = today + timedelta(days=1)
next_week = now + timedelta(weeks=1, hours=3)

# String formatting
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2024-12-15 14:30:45

python code snippet end

Timezone Handling

python code snippet start

from datetime import datetime, timezone

# UTC time
utc_now = datetime.now(timezone.utc)

# Convert between timezones
local_time = utc_now.astimezone()
print(f"UTC: {utc_now}")
print(f"Local: {local_time}")

python code snippet end

The datetime module handles calendar complexity so you can focus on application logic rather than temporal calculations.

Datetime operations often combine beautifully with f-string formatting for readable output and JSON serialization for data storage and APIs.

Reference: Python DateTime Module Documentation