Python Dates
Working with dates
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
2024-01-15 14:30:45.123456
The date contains year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. Here are some examples:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The strftime() Method
The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
A reference of all the legal format codes:
%a- Weekday, short version (Wed)%A- Weekday, full version (Wednesday)%w- Weekday as a number 0-6 (0 is Sunday)%d- Day of month 01-31%b- Month name, short version (Dec)%B- Month name, full version (December)%m- Month as a number 01-12%y- Year, short version, without century (18)%Y- Year, full version (2018)%H- Hour 00-23%I- Hour 00-12%p- AM/PM%M- Minute 00-59%S- Second 00-59