2

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 hour")
>>> one_hour == timedelta(hours=1)
>>> True

I would like to have powerful parsing capabilities and be able to parse rather generic timedelta representations such as: "2 minutes", "3 days", "1 year", etc.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Charlie
  • 1,750
  • 15
  • 20

2 Answers2

4

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)?')


def parse_time(time_str):
    parts = regex.match(time_str)
    if not 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
Bidhan Bhattarai
  • 1,040
  • 2
  • 12
  • 20
3

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

Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54
  • 1
    1- `dateparser` is a decent library. You could move the answer to [the duplicate question](http://stackoverflow.com/q/9775743/4279) 2- `.now()` return a naive datetime object that represents the local time that may be ambiguous. Don't use it in a time arithmetic -- you may get non-nonsensical results around DST transitions. See more details: [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/q/26313520/4279) – jfs Feb 26 '16 at 17:06