Python Dates
Python has no dedicated data type for dates. Instead, you import a module called datetime and work with dates as date objects.
Example
datetime module and display the current date and time using datetime.datetime.now().
Output: complete Python program
import datetime
x = datetime.datetime.now()
print(x)
Date Output
The output you see comes from running the code in the previous example.
A date value like this is made up of the year, month, day, hour, minute, second and microsecond.
Plenty of methods in the datetime module can tell you more about a date object.
Here is a small sample; the rest of this lesson covers more:
Example
datetime module, get the current date.
Print the year and the name of the weekday using strftime("%A").
Output: complete Python program
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Creating Date Objects
The datetime() class, a constructor in the datetime module, is what you call to create a date.
It needs three parameters: year, month and day.
You can also pass time and timezone values (hour, minute, second, microsecond, tzinfo). These are optional and default to 0, or None in the case of the timezone.
Example
datetime module and create a date object for May 17, 2020.
Use datetime.datetime(2020, 5, 17) and print it.
Output: complete Python program
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The strftime() Method
To turn a date object into a readable string, use a method of the datetime object.
That method is strftime(). Its single parameter, format, describes how the returned string should look:
These are the format codes you can use:
%a- Short weekday name (Wed)%A- Full weekday name (Wednesday)%w- Weekday number 0-6, with Sunday as 0 (3)%d- Day of the month, 01-31 (31)%b- Short month name (Dec)%B- Full month name (December)%m- Month number, 01-12 (12)%y- Two-digit year, no century (18)%Y- Four-digit year (2018)%H- Hour on a 24-hour clock, 00-23 (17)%I- Hour on a 12-hour clock, 01-12 (05)%p- AM or PM (PM)%M- Minute, 00-59 (41)%S- Second, 00-59 (08)%f- Microsecond, 000000-999999 (548513)%z- Offset from UTC (+0100)%Z- Timezone name (CST)%j- Day of the year, 001-366 (365)%U- Week of the year, 00-53, with weeks starting on Sunday (52)%W- Week of the year, 00-53, with weeks starting on Monday (52)%c- Date and time in local format (Mon Dec 31 17:41:00 2018)%C- Century (20)%x- Date in local format (12/31/18)%X- Time in local format (17:41:00)%%- Literal % character (%)%G- ISO 8601 year (2018)%u- Weekday number in ISO 8601, 1-7 (1)%V- ISO 8601 week number, 01-53 (01)
Example
datetime module and create a date object for June 1, 2018.
Use strftime("%B") to display the full month name.
Output: complete Python program
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))