I have incoming string data in format like "4w 2d 5h
" (weeks(w), days(d), hours(h), minutes(m)), some it can have different number of parameters (from 1 to 4, e.g "1w
", "2w 5h
", "3w 1d 5h 3m
", etc).
I need to convert it to timedelta (datetime) format.
The only way I know it is to split it and then use statements depending on the letter. But probably there is more efficient way?
CodePudding user response:
If you're sure the strings are well formatted then you could try to use re
:
import re
from datetime import timedelta
re_td = re.compile(r"(\d )(w|d|h|m)")
units = {"w": "weeks", "d": "days", "h": "hours", "m": "minutes"}
def to_timedelta(string):
return timedelta(**{units[u]: int(val) for val, u in re_td.findall(string)})
The pattern (\d )(w|d|h|m)
looks for numbers followed by one of the allowed letters, and due to the grouping a match in .findall
packs them into a tuple. If there could be whitespace between the number and the letter then use (\d )\s*(w|d|h|m)
instead.