Date & Time
Python's standard library offers powerful modules for handling dates, times, and calendar operations. These tools are essential for applications that require scheduling, logging, time zone management, or any form of temporal data processing. With built-in support for date arithmetic, formatting, and calendar utilities, developers can reliably manage time-related data without external dependencies.
The datetime and calendar modules are designed for clarity and precision, supporting both simple and complex use cases. Whether you need to parse timestamps, calculate durations, or generate custom calendars, these modules provide a consistent API and robust functionality.
Overview
- datetime: Create, manipulate, and format date/time objects; perform arithmetic and time zone conversions
- calendar: Generate calendars, check leap years, and perform calendar-based calculations
Key Features
- Native support for date/time arithmetic and comparison
- Time zone-aware datetime objects
- Flexible formatting and parsing of date/time strings
- Calendar generation and utility functions
- No external dependencies—fully included with Python
When to Use
- Applications requiring accurate date/time calculations (e.g., scheduling, logging)
- Time zone conversions and handling daylight saving time
- Generating or displaying calendars
- Parsing and formatting timestamps for interoperability
When Not to Use (or Alternatives)
- For advanced time zone support, use pytz or dateutil
- For high-performance time series analysis, consider pandas
- For internationalization and localization, use babel
Common Pitfalls
- Naive vs. aware datetime objects: Always specify time zones when working across regions
- String formatting: Use
strftimeandstrptimecarefully to avoid parsing errors - Leap years and daylight saving time can introduce subtle bugs—test edge cases
Example Usage
import datetime
import calendar
# Current date and time
now = datetime.datetime.now()
print(now.isoformat())
# Date arithmetic
yesterday = now - datetime.timedelta(days=1)
print(yesterday.strftime('%Y-%m-%d'))
# Time zone-aware datetime
from datetime import timezone
utc_now = datetime.datetime.now(timezone.utc)
print(utc_now)
# Calendar operations
print(calendar.month(2025, 8)) # August 2025 calendar
print(calendar.isleap(2024)) # True