The datetime
class in the datetime
module provide a structured approach in managing date and time data. It provides a wide range of tools and methods that enable easy manipulation of dates and time values.
In the above example, we used the now()
class method to get the current date and time values.
Timedelta objects, on the other hand, are used to represent a duration in terms of days, seconds, and microseconds.
A timedelta
can be defined as a difference between two dates or datetime
objects.
Performing arithmetic operations on datetimes
We can use the standard operators on datetime
objects. For example we can add two time to a objects together, subtract one from the other, compare two of them using comparison operators such as '<', '>', and '==', and access their individual components such as year, month, and day using dot notation.
Subtraction
Whenever we subtract two datetime
objects, as in above, a timedelta
is returned representing the time between the two days. We can also similarly subtract a timedelta
from a datetime
to get an earlier datetime
.
In the above example we instantiated a timedelta
object which holds a duration of one day. On subtracting now with the timdelta
we get yesterday's datetime
object.
Addition
When we add two datetime
objects, the result will be a timedelta
object representing the duration of time between the two datetime
objects. We can even more usefully add a timedelta
object to a datetime
object, and the result will be a new datetime
object that is the original datetime
plus the timedelta
duration.
Comparing datetimes
We can use comparison operators to compare datetime
objects in order to get the relation between them.