Write a Python program to convert two date difference in days,hours,minutes,seconds


This program calculates the time difference between two dates, which are the specified date (d1) and the current date (d2). The specified date is set to January 1st, 2020 at 1:00:00 AM, and it is converted to a datetime object using the datetime.strptime function. The datetime.now() function returns the current date and time.

The difference between the two dates is calculated by subtracting d1 from d2, which returns a timedelta object. The timedelta object contains the difference between the two dates in days, seconds, microseconds, milliseconds, minutes, hours, weeks, and years. In this program, the number of seconds in the timedelta object is extracted and then divided into minutes, hours, and days using the divmod function. The resulting values are printed to the console.

Source Code

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

Output

Days : 997
Hours : 12
Minutes : 31
Seconds : 49

Example Programs