Python Datetime: Working with Dates and Times
Learn how to handle dates, times, timezones, and calculations in Python. Master formatting, parsing, and arithmetic using datetime and timedelta.
Overview
Handling dates and times is a notorious challenge in software development, due to leap years, daylight saving adjustments, and differing timezone formats. Python resolves these challenges with its built-in `datetime` module. This module provides a robust set of object classes—such as `date`, `time`, `datetime`, and `timezone`—that represent and manipulate temporal data cleanly, making date calculations straightforward.
One of the most common tasks is converting dates to strings (formatting) and strings to dates (parsing). Python uses two main methods for this: `.strftime()` (string format time) converts a datetime object into a readable string using formatting codes (like `%Y` for year, `%m` for month, and `%d` for day). Conversely, `datetime.strptime()` (string parse time) parses a raw string input into a datetime object based on a matching format template, which is vital when reading logs or API inputs.
Performing date math is also fully supported using the `timedelta` object. A `timedelta` represents a duration of time (e.g., 7 days, 4 hours). You can add or subtract a `timedelta` from a `datetime` to calculate past or future dates (such as determining an expiration date). When working with multiple timezones, using timezone-aware objects (such as `zoneinfo` or `timezone.utc`) is critical to ensure date comparisons remain accurate across different server locations.
Code Example
Parsing strings into datetime objects and computing future deadlines using timedelta.
from datetime import datetime, timedelta
# Define a specific fixed base date and time (for deterministic runs)
base_date = datetime(2026, 5, 25, 23, 45, 50)
print(f"Base Date/Time: {base_date}")
# Format datetime as string
formatted = base_date.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted String: {formatted}")
# Parse string to datetime
date_str = "2026-12-25"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
print(f"Parsed Date: {parsed_date}")
# Date arithmetic with timedelta
ten_days_later = base_date + timedelta(days=10)
print(f"Date 10 days later: {ten_days_later.strftime('%Y-%m-%d')}")Base Date/Time: 2026-05-25 23:45:50
Formatted String: 2026-05-25 23:45:50
Parsed Date: 2026-12-25 00:00:00
Date 10 days later: 2026-06-04Real-world Use Cases
- Calculating trial expiration and billing dates
- Parsing timestamp strings inside server access logs
- Scheduling automated cron jobs or recurring reports
Frequently Asked Questions
What is a naive vs. aware datetime object?
A naive datetime object does not contain timezone information, whereas an aware datetime object includes timezone offsets, making it safe for international time calculations.
How do I calculate the difference between two dates?
Subtracting one datetime object from another returns a timedelta object representing the exact duration between them.
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
How to Parse a String to a Datetime in Python
Learn how to convert strings to datetime objects in Python. Master the strptime method, parse date strings, handle timezones, and prevent format errors.
Python DateTime Formatting
Learn how to parse and format dates and times in Python using datetime, strftime, and strptime.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.