Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert string to time format more than 24 hours format ( [h]:mm:ss ) without incrementing day

I need to convert string to time in hours format. I tried using the below But I didn’t get the results that I expect.

inp_string = "70:30:00"
print(datetime.strptime(inp_string, "%H:%M:%S").time())

For this I’m getting the following error:

ValueError: time data '70:30:00' does not match format '%H:%M:%S'

If I enter the value of hours below 24 I’m getting good results;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new = '23:30:00'
print("value:",datetime.strptime(new, "%H:%M:%S").time())
print(type(datetime.strptime(new, "%H:%M:%S").time()))

output

value: 23:30:00
<class 'datetime.time'>

Like this, I have to convert a string into time format where the hours are greater than 24.

>Solution :

You need to write your own parser to convert your str to timedelta (or find a library that does this for you).

Assuming your duration is always like HH:MM:SS, you can use something like this:

import datetime

def parse_duration(s):
    return list(map(lambda x: int(x), s.split(":")))

inp1 = "70:30:00"
[h1, m1, s1] = parse_duration(inp1)
d1 = datetime.timedelta(hours=h1, minutes=m1, seconds=s1)


inp2 = "00:30:00"
[h2, m2, s2] = parse_duration(inp2)
d2 = datetime.timedelta(hours=h2, minutes=m2, seconds=s2)

res = d1 + d2

# Format res however you like
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading