Add parse_duration to datetime - a golang like fucntion to parse duration
Hi Everyone, I really like how go parses durations: ``` hours, _ := time.ParseDuration("10h") complex, _ := time.ParseDuration("1h10m10s") micro, _ := time.ParseDuration("1µs") // The package also accepts the incorrect but common prefix u for micro. micro2, _ := time.ParseDuration("1us") ``` Consider the example in https://docs.python.org/3/library/datetime.html#timedelta-objects: ```
from datetime import timedelta delta = timedelta( ... days=50, ... seconds=27, ... microseconds=10, ... milliseconds=29000, ... minutes=5, ... hours=8, ... weeks=2 ... )
With a go like parsing it would be:
datetime.parse_duration("2w50d8h5m27s10ms2000us")
Go lang's implementation only supports "ns", "us" (or "µs"), "ms", "s", "m", "h", but that does not mean Python has to restirct itself to these units.
There a few similar pypi packages and SO answers with similar implementations, so there a basis to start from:
https://github.com/wroberts/pytimeparse
https://github.com/oleiade/durations
But the code can be as simple as this:
from datetime import timedelta
import re
regex = re.compile( r'((?P<weeks>[\.\d]+?)w)?' r'((?P<days>[\.\d]+?)d)?' r'((?P<hours>[\.\d]+?)h)?' r'((?P<minutes>[\.\d]+?)m)?' r'((?P<seconds>[\.\d]+?)s)?' r'((?P<microseconds>[\.\d]+?)ms)?' r'((?P<milliseconds>[\.\d]+?)us)?$' ) def parse_time(time_str): """ Parse a time string e.g. (2h13m) into a timedelta object. Modified from virhilo's answer at https://stackoverflow.com/a/4628148/851699 :param time_str: A string identifying a duration. (eg. 2h13m) :return datetime.timedelta: A datetime.timedelta object """ parts = regex.match(time_str) assert parts is not None, "Could not parse any time information from '{}'. Examples of valid strings: '8h', '2d8h5m20s', '2m4s'".format(time_str) time_params = {name: float(param) for name, param in parts.groupdict().items() if param} return timedelta(**time_params) print(repr(parse_time("2w50d8h5m27s10ms2000us"))) ``` This is an extended version of: https://stackoverflow.com/a/51916936/492620\ Is there someone willing to sponsor a PR for adding this to the STL? I'm willing to work on the code as well as the tests and documentation (I contributed small changes to docs.python.org and the `calendar` module in the past). Best regards, Oz
participants (7)
-
Alex Hall
-
Christopher Barker
-
Oz
-
Paul Moore
-
Richard Damon
-
Stephen J. Turnbull
-
tcphone93@gmail.com