Working with Dates and Times in Python: Using the Datetime Module
Learn how to handle dates and times in Python using the datetime
module. This guide shows you how to create date objects, retrieve details such as year and weekday, and display current date and time with examples.
Python Datetime
Python Dates
A date in Python is not a standalone data type, but we can use the datetime
module to work with dates as date objects.
Example
import datetime
x = datetime.datetime.now()
print(x)
Output
2024-07-02 13:20:35.770298
The date object includes year, month, day, hour, minute, second, and microsecond information.
The datetime
module provides various methods to retrieve details about the date object, such as year and weekday name.
Example
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Creating Date Objects
To create a specific date, use the datetime()
constructor from the datetime
module, which requires parameters for year, month, and day.
Example
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime()
constructor can also include optional parameters for time and timezone, defaulting to 0 and None respectively.
The strftime() Method
The strftime()
method formats date objects into readable strings using specified format codes.
Example
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Here are some common format codes:
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 05 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 08 |
%f | Microsecond 000000-999999 | 548513 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of the week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of the week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%C | Century | 20 |
%x | Local version of date | 12/31/18 |
%X | Local version of time | 17:41:00 |
%% | A % character | % |
%G | ISO 8601 year | 2018 |
%u | ISO 8601 weekday (1-7) | 1 |
%V | ISO 8601 week number (01-53) | 01 |