Home > Blockchain >  Convert String to datetime.timedelta
Convert String to datetime.timedelta

Time:04-07

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.

CodePudding user response:

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))
  • Related