How do you find the difference in time in Python
Chapter:
Python
Last Updated:
19-06-2023 17:31:42 UTC
Program:
/* ............... START ............... */
from datetime import datetime
# Create two datetime objects representing the points in time
start_time = datetime(2023, 6, 19, 10, 30, 0)
end_time = datetime(2023, 6, 19, 12, 45, 0)
# Calculate the time difference
time_difference = end_time - start_time
# Extract the difference in seconds
difference_in_seconds = time_difference.total_seconds()
# Print the difference
print("Difference in seconds:", difference_in_seconds)
# Extract the difference in minutes
difference_in_minutes = divmod(difference_in_seconds, 60)[0]
print("Difference in minutes:", difference_in_minutes)
# Extract the difference in hours
difference_in_hours = divmod(difference_in_minutes, 60)[0]
print("Difference in hours:", difference_in_hours)
/* ............... END ............... */
Output
Difference in seconds: 8100.0
Difference in minutes: 135.0
Difference in hours: 2.0
In this example, the difference between the start_time and end_time is 2 hours, 135 minutes, and 8100 seconds.
Notes:
-
In the above example, we create two datetime objects start_time and end_time representing the points in time you want to compare. We then calculate the time difference by subtracting start_time from end_time. The result is a timedelta object that represents the difference between the two times.
- To extract the difference in seconds, you can use the total_seconds() method of the timedelta object. If you want the difference in minutes or hours, you can use the divmod() function to perform integer division and get the quotient.
- Note that you need to have the correct date and time values in the datetime objects based on your specific use case.
Tags
How do you find the difference in time in Python # python time difference between two datetime