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) | 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:
