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'
CodePudding user response:
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.
CodePudding user response:
Unfortunately, it does not seem that there is no built in one liner. So in this case you can convert your datetime delta to seconds and than format it by manually counting h,m, seconds. One way would be to use python built-in function divmod()
:
from dateutil import parser
d1 = '2022-12-10T08:59:02Z'
d2 = '2022-12-10T10:06:35Z'
parsed_d1 = parser.parse(d1)
parsed_d2 = parser.parse(d2)
result = parsed_d2 - parsed_d1
# part from SO answer https://stackoverflow.com/a/539360/7489397
First we get total number of seconds (4053):
seconds = result.total_seconds()
After that calculate hours with divmod
- result is 1h(hour
) and 453seconds (remainder
)
hours, remainder = divmod(seconds, 3600)
After that minutes - 7minutes(minutes
), and 33seconds(seconds
)
minutes, seconds = divmod(remainder, 60)
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))