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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PJDKOK2CWNKO74PBHROH5ZSHMOQKBPXG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to