w3resource

Python: Calculate two date difference in seconds

Python Datetime: Exercise-36 with Solution

Write a Python program to calculate the difference between two dates in seconds.

Sample Solution:

Python Code:

# Import the datetime and time classes from datetime module
from datetime import datetime, time
# Define a function called date_diff_in_Seconds which calculates the difference in seconds between two datetime objects
def date_diff_in_Seconds(dt2, dt1):
    # Calculate the time difference between dt2 and dt1
    timedelta = dt2 - dt1
    # Return the total time difference in seconds
    return timedelta.days * 24 * 3600 + timedelta.seconds

# Specified date: January 1, 2015, at 01:00:00
date1 = datetime.strptime('2015-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')
# Current date and time
date2 = datetime.now()

# Print the time difference in seconds between the current date and the specified date
print("\n%d seconds" %(date_diff_in_Seconds(date2, date1)))
# Print an empty line
print()

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:

Flowchart: Calculate two date difference in seconds.

Python Code Editor:

Contribute your code and comments through Disqus.

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-36.php