Skip to content

Instantly share code, notes, and snippets.

@klenwell klenwell/natural_date.py
Last active Aug 29, 2015

Embed
What would you like to do?
Python parsedatetime library: enforce current year
#
# Natural Language Date Parsing
# http://stackoverflow.com/q/25089784/1093087
#
import parsedatetime as pdt
from datetime import datetime, date, timedelta
from time import mktime
import pdb
def natural_date(human_readable):
human_readable = human_readable.lower()
# Flag to cause parsedatetime to never go forward
# http://stackoverflow.com/a/25098991/1093087
ptc = pdt.Constants()
ptc.YearParseStyle = 0
cal = pdt.Calendar(ptc)
result, parsed_as = cal.parse(human_readable)
if not parsed_as:
raise ValueError("Unable to parse %s" % (human_readable))
return date.fromtimestamp(mktime(result))
def test_natural_date():
cases = [
# input, expect
('jan 1', date(date.today().year, 1, 1)),
('dec 31', date(date.today().year, 12, 31)),
('yesterday', date.today() - timedelta(days=1)),
('3 months before 12/31', date(date.today().year, 9, 30))
]
for human_readable, expect in cases:
result = natural_date(human_readable)
print("%s -> %s" % (human_readable, result))
assert result == expect, human_readable
test_natural_date()
pdb.set_trace()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.