Home > Mobile >  Convert two timestamps to time elapses in Python
Convert two timestamps to time elapses in Python

Time:08-06

I'm trying to get the time elapsed between two string timestamps in my Python code. Example:

Time Started: "2022-01-07 14:30"
Time Ended: "2022-01-07 15:45"

I want the answer to return as an int in number of minutes. So, in this example it would be 75 since that is the number of minutes elapsed between the starting and ending timestamps.

CodePudding user response:

You don't appear to have tried anything. Start with this:

  1. Call datetime.strptime() to convert to datetime objects
  2. Subtract the objects to get a timedelta
  3. Divide timedelta.total_seconds() by sixty to get the number of minutes

CodePudding user response:

from datetime import datetime
class Convert:
    def main(start,end):
        dt1=datetime.strptime(start, '%Y-%d-%m %H:%M')
        dt2=datetime.strptime(end, '%Y-%d-%m %H:%M')
        time1=str(dt1.time()).split(":")
        time2=str(dt2.time()).split(":")
        for i in range(0,len(time1)):
            time1[i]=int(time1[i])
        for j in range(0,len(time2)):
            time2[j]=int(time2[j])
        print(time1)
        hour_to_min1=time1[0]*60 time1[1] time1[2]
        hour_to_min2=time2[0]*60 time2[1] time2[2]
        print(hour_to_min1)
        print(hour_to_min2)
        total_time_taken=hour_to_min2-hour_to_min1
        print(f"The total time taken is {total_time_taken} minutes")

start=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))
end=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))

(Convert.main(start,end))

This was too simple....:)

  • Related