0

Is there an existing Python package that integrates with datetime and understands human-friendly date specification format, somewhat similar to how /usr/bin/date on GNU Linux does it?

$ date -d 'today'
Thu May 28 14:01:15 XXX 2015
$ date -d 'tomorrow'
Fri May 29 14:01:23 XXX 2015
$ date -d 'this Sunday'
Sun May 31 00:00:00 XXX 2015
$ date -d 'Wednesday next week'
Wed Jun 10 00:00:00 XXX 2015
bobah
  • 18,364
  • 2
  • 37
  • 70
  • 2
    Have a look at [parsedatetime](https://pypi.python.org/pypi/parsedatetime/?). Side note: `/usr/bin/date` only does as described when using GNU date. It's a non-standard extension, so don't expect this to work anywhere but on Linux. – dhke May 28 '15 at 13:10

2 Answers2

5

parsedatetime may be helpful:

import datetime as DT
import parsedatetime as pdt

p = pdt.Calendar()
for text in ('today', 'tomorrow', 'this Sunday', 'Wednesday next week', 'next week Wednesday', ):
    timetuple, flag = p.parse(text)
    date = DT.datetime(*timetuple[:6])
    print('{:20} --> {}'.format(text, date))

yields

today                --> 2015-05-28 09:00:00
tomorrow             --> 2015-05-29 09:00:00
this Sunday          --> 2015-05-31 09:13:46
Wednesday next week  --> 2015-06-01 09:00:00
next week Wednesday  --> 2015-06-03 09:00:00

But notice that Wednesday next week is parsed incorrectly.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

python-dateutil is another PyPI library which does fuzzy matches and input.

I personally have used delorean which has the sort of natural language features you mention such as:

>>> d.last_tuesday()
Delorean(datetime=2013-01-15 19:41:06.207481+00:00, timezone=UTC)
jvc26
  • 6,363
  • 6
  • 46
  • 75