Write a Python program to calculate two date difference in seconds


This program is written in Python and it imports the "datetime" class and the "time" class from the "datetime" module.

  • The line "d1 = datetime.strptime('2023-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')" creates a "datetime" object "d1" that represents the date and time "January 1st, 2023, 1:00:00 AM" . The "strptime" method of the "datetime" class is used to parse the date and time string "2023-01-01 01:00:00" and convert it to a "datetime" object. The format of the date and time string is specified as the second argument of the "strptime" method, with codes such as "%Y" for the year and "%H" for the hour.
  • The line "d2 = datetime.now()" creates a "datetime" object "d2" that represents the current date and time.
  • The line "timedelta = d2 - d1" calculates the difference between "d2" and "d1" and stores the result in a "timedelta" object. The "timedelta" object represents the difference between two "datetime" objects in terms of days, seconds, microseconds, milliseconds, minutes, hours, and weeks.
  • Finally, the line "print("Seconds :",timedelta.days * 24 * 3600 + timedelta.seconds)" calculates the number of seconds between "d2" and "d1" by first converting the number of days in "timedelta" to seconds, and then adding the number of seconds in "timedelta" . The result is printed to the console as "Seconds : [number of seconds]" .

Source Code

from datetime import datetime, time
#Specified date
d1 = datetime.strptime('2023-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')
#Current date
d2 = datetime.now()
timedelta = d2 - d1
print("Seconds :",timedelta.days * 24 * 3600 + timedelta.seconds)

Output

Seconds : -8508526

Example Programs