Search code examples
pythondatetimepython-datetimetimedeltapython-dateutil

Python Datetime Subtraction include 0 to hour section


I've 2 strings of datetime, I need to subtract those to get duration but when subtracted for hour section it only contain 1 digit eg: 1:30, 2:30 So, my question is can we get subtracted datetime or string which includes 0 at the beginning eg: 01:30, 02:30. Only for 1 - 9 hours include 0. Assume that there will be no recording with a length of more than a day.

d1 = '2022-12-10T08:59:02Z'
d2 = '2022-12-10T10:06:35Z'

For subtraction I use the code below.

from dateutil import parser

parsed_d1 = parser.parse(d1)
parsed_d2 = parser.parse(d2)

result = str(parsed_d2 - parsed_d1)
print(result)
>>> '1:07:33'

If you want to use datetime strptime or strftime then the format is

format = '%Y-%m-%dT%H:%M:%Sz'

Currently I'm getting the desired output by doing this

duration_list = result.split(":")
if int(duration_list[0]) <= 9:
    result = f"0{result}"
print(result)
>>> '01:07:33'

Solution

  • If the duration spans less than one day, you can also use strftime, after adding the duration to a datetime object where hours, minutes etc. are all zero, e.g. datetime.min. Ex:

    from datetime import datetime
    
    d1 = datetime.strptime('2022-12-10T08:59:02Z', '%Y-%m-%dT%H:%M:%S%z')
    d2 = datetime.strptime('2022-12-10T10:06:35Z', '%Y-%m-%dT%H:%M:%S%z')
    
    print((datetime.min + (d2-d1)).strftime("%H:%M:%S"))
    # 01:07:33
    

    Btw. this is similar to this answer to the question I linked in the comments.