Python: Calculate two date difference in seconds
36. Difference in Seconds
Write a Python program to calculate the difference between two dates in seconds.
Sample Solution:
Python Code:
Output:
74175795 seconds
Explanation:
In the exercise above,
- The code imports the "datetime" and "time" classes from the "datetime" module. which are necessary for working with date and time objects.
- It defines a function named "date_diff_in_Seconds()" which calculates the difference in seconds between two "datetime" objects.
- • Inside the function:
- It calculates the time difference (timedelta) between 'dt2' and 'dt1' using simple subtraction.
- It converts the time difference into seconds by multiplying the number of days by 24 hours and then by 3600 seconds, and adding the number of seconds in the "timedelta".
- It defines 'date1' as a specified date, January 1, 2015, at 01:00:00, using the "strptime()" function to parse the string into a "datetime" object.
- It defines 'date2' as the current date and time using the "datetime.now()" function.
- It prints the time difference in seconds between 'date2' and 'date1'.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to calculate the difference in seconds between two given dates and times using datetime arithmetic.
- Write a Python script that computes the total seconds between two datetime objects and then formats the result into hours, minutes, and seconds.
- Write a Python function to determine the number of seconds between a user-input start and end datetime, and then check if the result exceeds a threshold.
- Write a Python program to take two datetime strings, convert them, and then output the difference in seconds along with a message indicating if it is less than an hour.
Go to:
Previous: Write a Python program to convert a date to Unix timestamp.
Next: Write a Python program to convert two date difference in days, hours, minutes, seconds.
Python Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.