datetime module provides classes for working with dates, times, and time intervals.
Module Import
datetime Class
Represents a specific date and time.Creating datetime Objects
Accessing Components
Formatting datetime
Format Codes
Date Format Codes
Date Format Codes
%Y- Year with century (2024)%y- Year without century (24)%m- Month as number (01-12)%B- Full month name (January)%b- Abbreviated month (Jan)%d- Day of month (01-31)%j- Day of year (001-366)
Time Format Codes
Time Format Codes
%H- Hour 24-hour (00-23)%I- Hour 12-hour (01-12)%M- Minute (00-59)%S- Second (00-59)%f- Microsecond (000000-999999)%p- AM/PM
Weekday Format Codes
Weekday Format Codes
%A- Full weekday name (Monday)%a- Abbreviated weekday (Mon)%w- Weekday as number (0=Sunday)%W- Week number of year (00-53)
date Class
Represents a date (year, month, day) without time.time Class
Represents a time (hour, minute, second, microsecond) without date.timedelta Class
Represents a duration or difference between dates/times.Creating timedelta
Arithmetic with datetime
timedelta Components
timezone and tzinfo
Timezone-Aware datetime
Working with Timezones
Practical Examples
Age Calculator
Days Until Event
Working Hours Calculator
Timestamp Conversion
Date Range Generator
Week Number and Day
Parse Multiple Date Formats
Constants
Best Practices
Be careful with datetime arithmetic across DST boundaries:
Use proper timezone libraries like
zoneinfo for complex timezone handling.Related Modules
time
Time access and conversions
zoneinfo
IANA time zone support
calendar
General calendar functions
