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
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
-
yearreturns 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
If time values are not provided, they default to 00:00:00.
Example: Create a Date with Time
Formatting Dates with strftime()
The strftime() method converts a datetime object into a
human-readable string using format codes.
Example: Display Month Name
Common strftime() Format Codes
| Code | Meaning | Example |
|---|---|---|
%a
|
Weekday (short) | Sat |
%A
|
Weekday (full) | Saturday |
%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) | 45 |
%W
|
Week number (Monday start) | 45 |
%c
|
Full date & time | Sat 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
%a→ Short weekday name%A→ Full weekday name
Day of Month
-
%d→ Day of the month (01–31)
Month Formats
%b→ Short month name%B→ Full month name%m→ Month number
Year Formats
%y→ Year (2 digits)%Y→ Year (4 digits)
Hour Formats
-
%H→ Hour (24-hour format) -
%I→ Hour (12-hour format) %p→ AM / PM
Minute, Second, Microsecond
%M→ Minutes%S→ Seconds%f→ Microseconds
Day & Week Information
%j→ Day of the year-
%U→ Week number (Sunday as first day) -
%W→ Week number (Monday as first day)
Full Date & Time Formats
%c→ Full date and time%x→ Local date%X→ Local time
Percent Symbol
-
%%→ Prints a literal % symbol
