Introduction to Python's datetime Module
If you're a Python developer, you've likely encountered the need to handle dates and times. Whether it's logging
events, scheduling tasks, or analyzing time-series data, Python's built-in datetime module is your best
friend. In this guide, we'll master the core concepts and best practices for managing time in Python.
The Core Classes
The datetime module offers several classes, but you'll primarily work with these three:
datetime.date: Represents a date (year, month, day).datetime.time: Represents a time (hour, minute, second, microsecond).datetime.datetime: Combines date and time into a single object.datetime.timedelta: Represents a duration or difference between two dates/times.
1. Getting the Current Date and Time
The most common starting point is getting the "now".
from datetime import datetime
# Current local date and time
now = datetime.now()
print(f"Now: {now}")
# Current UTC date and time
now_utc = datetime.utcnow()
print(f"UTC Now: {now_utc}")
datetime.now() returns a "naive" datetime object (without timezone info).
For timezone-aware applications, always use UTC or libraries like zoneinfo.
2. Formatting and Parsing (strftime & strptime)
Converting between strings and datetime objects is a daily task. Mnemonic: f for Format (to string), p for Parse (from string).
# Formatting: datetime object -> string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted_date}")
# Parsing: string -> datetime object
date_string = "2023-12-25 10:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed: {parsed_date}")
Common codes:
%Y: Year (e.g., 2024)%m: Month (01-12)%d: Day (01-31)%H: Hour (00-23)%M: Minute (00-59)%S: Second (00-59)
3. Calculating Differences with timedelta
Want to find out what the date will be in 7 days? Or calculate how long a script took to run? Use
timedelta.
from datetime import timedelta
# Add 7 days to current date
future_date = now + timedelta(days=7)
print(f"Next week: {future_date}")
# Subtract 2 hours
past_time = now - timedelta(hours=2)
print(f"2 hours ago: {past_time}")
# Calculate duration
start = datetime.now()
# ... heavy processing ...
end = datetime.now()
duration = end - start
print(f"Took {duration.total_seconds()} seconds")
4. Validating Timezones (The Right Way)
Since Python 3.9, the zoneinfo module is the standard for timezone support (replacing `pytz` for many
use cases).
from zoneinfo import ZoneInfo
# Create a timezone-aware datetime
ny_time = datetime.now(ZoneInfo("America/New_York"))
print(f"NY Time: {ny_time}")
# Convert to London time
london_time = ny_time.astimezone(ZoneInfo("Europe/London"))
print(f"London Time: {london_time}")
Conclusion
Python's datetime module is powerful and flexible. By understanding the difference between naive and
aware objects and mastering timedelta, you can handle almost any temporal challenge your application
throws at you.
🚀 Quick Tips
- Always store dates in UTC in your database.
- Only convert to local time when displaying to the user.
- Use
isoformat()for API responses.