How to get Number of Seconds between Two Dates in Python?

Python – Get Number of Seconds between Two Dates

To get the number of seconds between two given dates in Python, follow these steps.

  • Import datetime library.
  • Take the two dates as date objects.
  • Find the difference between these two dates using Subtraction Operator. Subtraction Operator with the two dates as operands returns a timedelta object.
  • timedelta.total_seconds() returns the number of seconds between the two given dates.

Program

In the following program, we take two dates: date_1 and date_2 as date objects, and find the number of seconds between them.

Python Program

from datetime import date

date_1 = date(2022, 1, 18)
date_2 = date(2022, 2, 14)
diff = date_2 - date_1
seconds = diff.total_seconds()
print('Number of seconds :', seconds)
Run Code Copy

Output #1

Number of seconds : 2332800.0

There are 27 days between the two given dates, and therefore 27 days * 24 hours * 60 minutes * 60 seconds is equal to 2332800 seconds.

Summary

In this Python Tutorial, we learned how to find the number of seconds between two given dates, using datetime library.

Code copied to clipboard successfully 👍