In today’s Python automation tutorial we would like to show how you can easily subtract and calculate time differences using the Python language.
We’ll use the datetime module to calculate:
- Difference between two dates
- Difference between a date and a timedelta object.
- Subtracting other timedeltas from date objects : years, months, hours, minutes, seconds.
Subtract days from a datetime object in Python
Let’s define two date objects that represents the hire and quitting date of a random employee.
import datetime
hire_date = datetime.date(2021,4, 7)
quit_date = datetime.date(2022,4, 24)
Then let’s calculate the overall time worked:
print("The overall time that this employee worked in our company was:" + str(quit_date - hire_date).split(',')[0]+".")
Here’s the result:
The overall time that this employee worked in our company was:382 days.
Subtract timedeltas from datetimes
We’ll now define a datetime and timedelta representing the hire date and the number of days on the job for our fictitious employee:
import datetime
hire_date = datetime.date(2021,4, 7)
worked_days = datetime.timedelta(282)
Let’s quickly calculate the quitting date of this employee:
print("The hire date of this employee worked in our company was: " + str(quit_date - worked_days)+".")
Here’s the result:
The hire date of this employee worked in our company was: 2021-06-08.
Note: Another way to accomplish this would have been using the dateutil.relativedelta method
print(quit_date - relativedelta(days = 282))
Subtract years from datetime
The dateutil.relativedelta utility allows to very easily subtract time from a date object.
from dateutil.relativedelta import relativedelta
graduation_date = quit_date - relativedelta(years = 2)
print("His graduation date was on: " + str(graduation_date))
The result will be:
His graduation date was on: 2020-04-24
Note: Don’t forget to import the utility into your Python program as otherwise you will receive the following NameError:
NameError: name 'relativedelta' is not defined
Subtract months from a Python date
As we just learnt, we can use the relativedelta utility to calculate time differences relative to a Python daytime / timestamp.
The following code helps to subtract 24 months from a datetime:
from dateutil.relativedelta import relativedelta
graduation_date = quit_date - relativedelta(months = 24)
print("His graduation date was on: " + str(graduation_date))
Find time differences in hours, minutes and seconds
In a similar fashion we can subtract any time units from our datetime:
- Seconds: graduation_date = quit_date – relativedelta(seconds=500000)
- Minutes:quit_date – relativedelta(minutes=45255)