Python DateTime Difference – 0 days, 1 hour, 5 minutes, and 8 seconds

In this little Python example I will show how to calculate the different between two datetime objects and display the difference in the format 0 DAYS, 1 HOURS, 5 MINUTES AND 8 SECONDS

import datetime

# datetime.datetime(year, month, day, hour, minute, second)
startTime = datetime.datetime(2020,3,23,10,7,34)

# endTime is now
endTime = datetime.datetime.now()

# Calculate the difference
runTime = endTime - startTime

# Covert the difference from datetime to the total number of seconds
runTime_in_s =  runTime.total_seconds()

# Use divmod to cacluate the days, hours, minuets and seconds
runtimeDays    = divmod(runTime_in_s, 86400)        # Get days (without [0]!)
runtimeHours   = divmod(runtimeDays[1], 3600)               # Use remainder of days to calc hours
runtimeMinutes = divmod(runtimeHours[1], 60)                # Use remainder of hours to calc minutes
runtimeSeconds = divmod(runtimeMinutes[1], 1)               # Use remainder of minutes to calc seconds

# Print the result
print("Difference: %d days, %d hours, %d minutes and %d seconds" % (runtimeDays[0], runtimeHours[0], runtimeMinutes[0], runtimeSeconds[0]))

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.