Home > Software engineering >  Python ,Duration Calcution between Timestamps
Python ,Duration Calcution between Timestamps

Time:11-01

I'm working on backend ,Short Explanation :

I have 2 timestamps which are in this format "2022-10-29T16:30:00 05:30","2022-10-29T17:30:00 05:30" .I need to calculate this duration between these but I tried to figure out the format of this timestamp,so I could calculate using datetime method in python.

CodePudding user response:

This uses the method datetime.fromisoformat(date_string) to convert the ISO 8601-formatted string into a datetime object. From there, you can subtract to find the time difference. Additionally, you may want to add some code to check for negative results, or you can simply use the function abs(x).

import datetime


def duration_between(ts_1: str, ts_2: str) -> datetime.datetime:
    ts_1_dt = datetime.datetime.fromisoformat(ts_1)
    ts_2_dt = datetime.datetime.fromisoformat(ts_2)
    return ts_2_dt - ts_1_dt


ts_1 = "2022-10-29T16:30:00 05:30"
ts_2 = "2022-10-29T17:30:00 05:30"

delta: datetime.datetime = duration_between(ts_1, ts_2)
print(delta)  # 1:00:00
print(delta.total_seconds())  # 3600.0

To obtain the delta in other common formats (years, days, hours, minutes, seconds, microseconds), see this answer: https://stackoverflow.com/a/47207182/11597788

  • Related