Dates and Times
Last updated
Last updated
This section discusses the operations on dates and times in the Python standard library.
is a module that provides a number of classes for manipulating dates and times. For example, we can use it to create a date object, a time object, or a datetime object.
Results are like this:
These objects have some properties that can be accessed. For example, the date object has a year
, month
, and day
property.
The time object has a hour
, minute
, and second
property.
The datetime object has a year
, month
, day
, hour
, minute
, and second
property.
We can use weekday()
to get the day of the week for a date. For example, the day of the week for the date 2020-11-18
is Friday
.
It will print Friday
. The weekday()
method returns an integer between 0 and 6, where 0 is Monday and 6 is Sunday.
date
, time
, and datetime
objects are immutable. We need to use the replace()
method to create a new object with a different value for one of the properties.
This will print 2021-11-18
. We can also use the replace()
method to change the time or datetime object.
An example of formatting a date, a time and a datetime object:
We can perform calculations on dates and times using timedelta()
. For example, we can use the timedelta()
method to calculate the number of days between two dates. Dates and times can be compared using the <
, >
, <=
, >=
, ==
, and !=
operators.
Output is going to be 32
, False
, and True
. timedelta()
can be used to perform date math. An example:
The main way to format dates and times is to use the strftime()
method. For example, we can use the strftime()
method to format the date 2020-11-18
as November 18, 2020
. For more information, see .