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?
Asked
Active
Viewed 65 times
0

Lim Jun Yu
- 44
- 2
-
4what have you tried so far? – bb1950328 Jan 04 '22 at 13:51
-
See here as a starting point: https://stackoverflow.com/questions/466345/converting-string-into-datetime – Jean-Marc Volle Jan 04 '22 at 13:52
-
Here's some approaches: https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string – tzaman Jan 04 '22 at 13:52
-
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jan 11 '22 at 17:49
1 Answers
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