How To Parse Timedelta From Strings
Is there any package for python 2.7 which would allow me to do something like this: >>> from datetime import timedelta >>> one_hour == the_lib_i_want.parse('1
Solution 1:
This library looks like a way for you: https://dateparser.readthedocs.org/en/latest/
It isn't exactly solution, but it may parse something like you mentioned above, so you can use current datetime and produced by the library to get timedelta.
So you can do something like:
import dateparser
import datetime
datetime.datetime.now() - dateparser.parse('1 hour ago')
I know it isn't what you want but perhaps it may help
Solution 2:
Here's my implementation using re
. It is very close to what you need
import re
from datetime import timedelta
regex = re.compile(r'((?P<hours>\d+?)hr)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?')
defparse_time(time_str):
parts = regex.match(time_str)
ifnot parts:
return
parts = parts.groupdict()
time_params = {}
for (name, param) in parts.iteritems():
if param:
time_params[name] = int(param)
return timedelta(**time_params)
>>> parse_time('1hr')==timedelta(hours=1)
True>>> parse_time('3hr10s')==timedelta(hours=3,seconds=10)
True>>> parse_time('10s')==timedelta(seconds=120)
False
Post a Comment for "How To Parse Timedelta From Strings"