How to do date and time calculations in Python?
How to Perform Date and Time Calculations in Python?
Performing date and time calculations in Python is very easy using timedelta objects. Whenever you want to add or subtract a date/time, use datetime.datetime() and then add or subtract a datetime.timedelta() instance. A timedelta object represents a duration, that is, the difference between two dates or times. The timedelta constructor has the following function signature –
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note: All parameters are optional and default to 0. Parameters can be of type int, long, or float and can be positive or negative. You can learn more here – https://docs.python.org/2/library/datetime.html#timedelta-objects
For more Python-related articles, read: Python Tutorial
Example
An example of timedelta objects and dates –
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
Output
This will give the output –
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
timedelta() does not support arithmetic operations with datetime.time() objects; if you need to use an offset from an existing datetime.time() object, use datetime.datetime.combine() to form a datetime.datetime() instance, perform the calculation, and then use the .time() method to extract the time again.
Subtracting two datetime objects produces a timedelta object. This timedelta object can be used to find the exact difference between two dates.
Example
t1 = datetime.datetime.now()
t2 = datetime.datetime.now()
print(t1 - t2)
print(type(t1 - t2))
Output
This will give the output –
-1 day, 23:59:56.653627
<class 'datetime.timedelta'>