ChrisGuest ChrisGuest - 3 months ago 15
Python Question

Parsing human readable relative times

I would like to parse human terms like

3 days ago
in
python 2.7
to get a timedelta equivalent.

For example:

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


I have tried the
dateparser
module.

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


It parses relative time directly to
datetime
without the option of returning a
timedelta
. 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

You could specify the RELATIVE_BASE setting:

>>> now = datetime.datetime.now()
>>> res = dateparser.parse('3 days ago', settings={'RELATIVE_BASE': now})
>>> now - res
datetime.timedelta(3)