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 datetime.timedelta

I have an input string as hundreds or thousand of hours, such as:

1000:50 (One thousand hours and 50 minutes)

I need to convert it into a timedelta object, in order to insert it as a DurationField in a Django Model.
So far, what I tried is to use datetime.strptime but, the error is giving me is:

time data '1000:50' does not match format '%H:%M'

I tried to google any kind of solution but so far I didn’t find a solution that could help me. Even though the DurationField will convert the timedelta in number of days, I just need to have the input to be as thousand or hundreds of hours, after that, the calculation will be handled in the backend.

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

>Solution :

You get an error because %H only for 24 hours format, i.e. 0…23

To solve your particular problem, I’d extract hours and minutes from string via regular expressions

import re
from datetime import timedelta


your_string = "1000:50 (One thousand hours and 50 minutes)"
hours, minutes = re.findall('(\d+):(\d+)', your_string)[0]
duration = timedelta(hours=int(hours), minutes=int(minutes))
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