Python datetime Module
Python does not have a standalone date data type. Instead, it provides the powerful datetime module, which allows you to work with dates, times, and timestamps using dedicated objects.
To begin working with dates, you must first import the module.
Getting the Current Date and Time
You can retrieve the current local date and time using the now()
method.
Example: Display the Current Timestamp
Output:
This output includes:
• Year
• Month
• Day
• Hour
• Minute
• Second
• Microsecond
Extracting Date Components
A datetime object provides easy access to individual date and time values.
Example: Get Year and Weekday
Output:
Weekday: Tuesday
• year returns the numeric year
• strftime("%A") returns the full weekday name
Creating Custom Date Objects
You can create your own date and time values using the datetime()
constructor.
Required Parameters
• year
• month
• day
Optional Parameters
• hour
• minute
• second
• microsecond
• Tzinfo
Example: Create a Specific Date
Output:
If time values are not provided, they default to 00:00:00.
Example: Create a Date with Time
Output:
Formatting Dates with strftime()
The strftime() method converts a datetime object into a human-readable
string using format codes.
Example: Display Month Name
Output:
Common strftime() Format Codes
| Code | Meaning | Example |
|---|---|---|
%a | Weekday (short) | Tue |
%A | Weekday (full) | Tuesday |
%d | Day of month | 09 |
%b | Month (short) | Nov |
%B | Month (full) | November |
%m | Month number | 11 |
%y | Year (2 digits) | 25 |
%Y | Year (4 digits) | 2025 |
%H | Hour (24-hour) | 18 |
%I | Hour (12-hour) | 06 |
%p | AM / PM | PM |
%M | Minute | 45 |
%S | Second | 30 |
%f | Microsecond | 123456 |
%j | Day of the year | 320 |
%U | Week number (Sunday start) | 47 |
%W | Week number (Monday start) | 47 |
%c | Full date & time | Tue Nov 15 18:45:30 2025 |
%x | Local date | 11/15/25 |
%X | Local time | 18:45:30 |
%% | Percent symbol | % |
Python strftime() Format Codes – Complete Examples
We’ll use this datetime object in all examples:
Weekday Formats
Output:
Tuesday
• %a → Short weekday name
• %A → Full weekday name
Day of Month
Output:
• %d → Day of the month (01–31)
Month Formats
Output:
November
11
• %b → Short month name
• %B → Full month name
• %m → Month number
Year Formats
Output:
2025
• %y → Year (2 digits)
• %Y → Year (4 digits)
Hour Formats
Output:
06
PM
• %H → Hour (24-hour format)
• %I → Hour (12-hour format)
• %p → AM / PM
Minute, Second, Microsecond
Output:
30
123456
• %M → Minutes
• %S → Seconds
• %f → Microseconds
Day & Week Information
Output:
46
46
• %j → Day of the year
• %U → Week number (Sunday as first day)
• %W → Week number (Monday as first day)
Full Date & Time Formats
Output:
11/15/25
18:45:30
• %c → Full date and time
• %x → Local date
• %X → Local time
Percent Symbol
Output:
• %% → Prints a literal % symbol
