Python Online Compiler
Example: Difference Between Two Time Periods in Python using datetime module
C
C++
C#
Java
Python
PHP
main.py
STDIN
Run
# DIFFERENCE BETWEEN TWO TIME PERIODS in Python using datetime module from datetime import datetime # Step-1 Define the start and end time using datetime objects start_time = datetime(2025, 6, 3, 8, 20, 45) end_time = datetime(2025, 6, 11, 14, 5, 30) # Step-2 Subtract the two to get a timedelta object difference = end_time - start_time # Step-3 Extract total seconds and convert to hours, minutes, seconds total_seconds = int(difference.total_seconds()) hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 # Step-4 Display the time difference print(f"\nTIME DIFFERENCE: {hours} HOURS, {minutes} MINUTES, {seconds} SECONDS")
Output
Clear
ADVERTISEMENTS