Date and Time
Date and Time
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:
When you run the program, the output will be something like:
2018-12-19 09:26:03.478039
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)
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)
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%j Day number of year 001-366 365
%% A % character %