Python program to find difference between two timestamps

PythonServer Side ProgrammingProgramming

Suppose we have two times in this format "Day dd Mon yyyy hh:mm:ss +/-xxxx", where Day is three letter day whose first letter is in uppercase. Mon is the name of month in three letters and finally + or - xxxx represents the timezone for example +0530 indicates it is 5 hours 30 minutes more than GMT (other formats like dd, hh, mm, ss are self-explanatory). We have to find absolute difference between two timestamps in seconds.

To solve this using python we will use the datetime library. There is a function called strptime() this will convert string formatted date to datetime object. There are few format specifiers like below −

  • %a indicates the day in three letter format
  • %d indicates day in numeric format
  • %b indicates month in three letter format
  • %Y indicates year in yyyy format
  • %H indicates hour in hh format
  • %M indicates minutes in mm format
  • %S indicates seconds in ss format
  • %z indicates the timezone in +/- xxxx format

So, if the input is like t1 = "Thu 15 Jul 2021 15:10:17 +0530" t2 = "Thu 15 Jul 2021 20:25:29 +0720", then the output will be 12312

To solve this, we will follow these steps −

  • t1 := change first time format from given string to above mentioned format
  • t2 := change second time format from given string to above mentioned format
  • return difference between t1 and t2 in seconds

Example

Let us see the following implementation to get better understanding −

from datetime import datetime

def solve(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")
   return abs(int((t1-t2).total_seconds()))

t1 = "Thu 15 Jul 2021 15:10:17 +0530"
t2 = "Thu 15 Jul 2021 20:25:29 +0720"
print(solve(t1, t2))

Input

"Thu 15 Jul 2021 15:10:17 +0530", "Thu 15 Jul 2021 20:25:29 +0720"

Output

12312
raja
Published on 12-Oct-2021 07:46:04
Advertisements