Python program to find difference between two timestamps

When working with timestamps in different timezones, you often need to calculate the time difference between them. Python's datetime library provides powerful tools to parse timestamp strings and compute differences accurately.

The timestamp format "Day dd Mon yyyy hh:mm:ss +/-xxxx" includes timezone information, where +/-xxxx represents the offset from GMT (e.g., +0530 means 5 hours 30 minutes ahead of GMT).

Understanding Format Specifiers

The strptime() function uses format specifiers to parse timestamp strings ?

  • %a ? Day in three letter format (Thu, Fri, etc.)
  • %d ? Day in numeric format (01-31)
  • %b ? Month in three letter format (Jan, Feb, etc.)
  • %Y ? Year in yyyy format (2021, 2022, etc.)
  • %H ? Hour in 24-hour format (00-23)
  • %M ? Minutes (00-59)
  • %S ? Seconds (00-59)
  • %z ? Timezone offset (+0530, -0800, etc.)

Example

Let's calculate the difference between two timestamps from different timezones ?

from datetime import datetime

def solve(t1, t2):
    # Parse both timestamp strings into datetime objects
    t1 = datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z")
    t2 = datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z")
    
    # Calculate absolute difference in seconds
    return abs(int((t1 - t2).total_seconds()))

# Example timestamps from different timezones
t1 = "Thu 15 Jul 2021 15:10:17 +0530"
t2 = "Thu 15 Jul 2021 20:25:29 +0720"

difference = solve(t1, t2)
print(f"Time difference: {difference} seconds")
Time difference: 12312 seconds

How It Works

The function converts both timestamp strings to timezone-aware datetime objects. When calculating the difference, Python automatically handles the timezone conversion, ensuring accurate results regardless of the timezone differences.

Converting to Hours and Minutes

For better readability, you can convert seconds to hours, minutes, and seconds ?

from datetime import datetime

def time_difference_detailed(t1, t2):
    t1 = datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z")
    t2 = datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z")
    
    total_seconds = abs(int((t1 - t2).total_seconds()))
    
    hours = total_seconds // 3600
    minutes = (total_seconds % 3600) // 60
    seconds = total_seconds % 60
    
    return hours, minutes, seconds

t1 = "Thu 15 Jul 2021 15:10:17 +0530"
t2 = "Thu 15 Jul 2021 20:25:29 +0720"

hours, minutes, seconds = time_difference_detailed(t1, t2)
print(f"Difference: {hours} hours, {minutes} minutes, {seconds} seconds")
Difference: 3 hours, 25 minutes, 12 seconds

Conclusion

Use datetime.strptime() with proper format specifiers to parse timestamp strings with timezone information. The total_seconds() method provides the difference in seconds, and Python automatically handles timezone conversions for accurate calculations.

Updated on: 2026-03-26T15:37:38+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements