T
T
timka2282021-04-11 16:49:57
Python
timka228, 2021-04-11 16:49:57

How to convert string to timedelta in Python?

I am working with the datetime library.
There is such a timedelta in a string: How to convert this into a real timedelta for subsequent calculations with dates? timedelta could also be like this:
timedelta_str = '1 days, 0:00:00'
timedelta_str = '1:30:00'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-04-11
@timka228

There are no existing methods (or maybe there are), make your parser based on the desired format. Something like:

def parse_timedelta(timedelta_str):

    pattern = re.compile(r'((?P<days>\d+) days, )?(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+)')
    m = pattern.match(timedelta_str)

    params = {key: float(val) for key, val in m.groupdict(0).items()}

    return timedelta(**params)

print(parse_timedelta('1 days, 0:00:25'))
print(parse_timedelta('0:00:25'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question