6

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?

2 Answers 2

6

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)
1
  • 1
    Thank you. I had looked on the readthedocs page, but that particular feature was not clearly documented.
    – ChrisGuest
    Commented Aug 23, 2016 at 4:10
1

I would just like to tip about the interesting Arrow library that has a builtin dehumanize() method. The dehumanize() method takes a human readable string and use it to shift a moment into a past time or into the future. The above could then be accomplished as simply as:

>>> import arrow
>>> now = arrow.now()
<Arrow [2021-10-15T14:43:20.506200+02:00]>
>>> now.dehumanize('3 days ago')
<Arrow [2021-10-12T14:43:20.506200+02:00]>
>>> now.dehumanize('3 days ago') - now
datetime.timedelta(days=-3)

Not the answer you're looking for? Browse other questions tagged or ask your own question.