ChrisGuest ChrisGuest - 1 year ago 98
Python Question

Parsing human readable relative times

I would like to parse human terms like

3 days ago
python 2.7
to get a timedelta equivalent.

For example:

>>> relativetimeparer.parser('3 days ago')

I have tried the

>>> import dateparser
>>> dateparser.parse('3 days ago')
datetime.datetime(2016, 8, 20, 2, 57, 23, 372538)
>>> - dateparser.parse('3 days ago')
datetime.timedelta(3, 35999, 999232)

It parses relative time directly to
without the option of returning a
. It also seems to think that 3 days ago is actually 3 days and 10 hours ago. So it seems to be invoking my timezone offset from Greenwich too (+10 hours).

Is there a better module for parsing human readable relative times?

Answer Source

You could specify the RELATIVE_BASE setting:

>>> now =
>>> res = dateparser.parse('3 days ago', settings={'RELATIVE_BASE': now})
>>> now - res
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download