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.
Example
Import the datetime module and display the current date:
Example 1: Get Current Date and Time
1. import datetime
2.
3. datetime_object = datetime.datetime.now()
4. print(datetime_object)
When you run the program, the output will be something like:
2018-12-19 09:26:03.478039
Here, we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class. We then
used now() method to create a datetime object containing the current local date and
time.
Example 2: Get Current Date
1.
2. import datetime
3.
4. date_object = datetime.date.today()
5. print(date_object)
When you run the program, the output will be something like:
2018-12-19
In this program, we have used today() method defined in the date class to get
a date object containing the current local date.
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.
Example
Create a date object:
import datetime
x = datetime.date(2020, 5, 17)
print(x)
Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily. Here's
how:
1.
2. from datetime import date
3.
4. # date object of today's date
5. today = date.today()
6.
7. print("Current year:", today.year)
8. print("Current month:", today.month)
9. print("Current day:", today.day)
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:
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
A reference of all the legal format codes:
Directive Description Example Try it
%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 week, 00-53 52
%W Week number of year, Monday as the first day of week, 00- 52
53
%c Local version of date and time Mon Dec 31 17:41:00
2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %