0

So basically, I have a question which has already bothering me for time. What I am trying to do is parse the time like 10m10s or 5d6w like that, into 10 minutes and 10 seconds, 6 weeks and 5 days (or 1 month, 2 weeks and 5 days) accordingly. Is there a fast way or nice solution for it?

Lim Jun Yu
  • 44
  • 2

1 Answers1

1

Assuming the format is always <number><identifier> with identifiers as

d   # day
s   # second
µs  # microsecond
ms  # millisecond
m   # minute
h   # hour
w   # week

You could use a regex coupled with datetime.timedelta:

import re
from datetime import timedelta

s1 = '10m10s1d1w1d8ms'

# extract the parameters in order of `timedelta`
reg = re.compile(r'(\d+)d|(\d+)s|(\d+)µs|(\d+)ms|(\d+)m|(\d+)h|(\d+)w')

# sum the identical units to form a single list
params = [sum(int(e) for e in t if e) for t in zip(*reg.findall(s1))]

# create a timedelta object
t = timedelta(*params)

output:

datetime.timedelta(days=9, seconds=610, microseconds=8000)

NB. The order of the parameters of timedelta is:

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
as a function
def str_to_tdelta(s):
    import re
    from datetime import timedelta
    reg = re.compile(r'(\d+)d|(\d+)s|(\d+)µs|(\d+)ms|(\d+)m|(\d+)h|(\d+)w')
    params = [sum(int(e) for e in t if e) for t in zip(*reg.findall(s))]
    return timedelta(*params)


str_to_tdelta('5d6w')
# datetime.timedelta(days=47)
mozway
  • 194,879
  • 13
  • 39
  • 75