How to subtract dates and times in Python?

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:

  1. Difference between two dates
  2. Difference between a date and a timedelta object.
  3. 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))

Substract years from datetime

The dateutil.relativedelta method 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

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)

Additional learning

How to get the difference between two dates in Pandas?