Intelligent Date & Time parsing

shakefu at gmail.com shakefu at gmail.com
Fri Mar 7 22:23:46 EST 2008


I figured I might as well share the code I ended up using, in case
anyone else wants an easy way to get strings to, for instance, SQL-
storable datetimes.

jake at house:~$ cat test.py
#!/usr/bin/python
from datetime import datetime
import subprocess

def parsedate( date ):
    p = subprocess.Popen(['date','+%s.%N',"--date=%s" %
date],stdout=subprocess.PIPE)
    out = float(p.stdout.read())
    return "%s" % datetime.fromtimestamp(out)

jake at house:~$ python -i test.py
>>> parsedate("today")
'2008-03-07 21:20:31.870489'
>>> parsedate("tomorrow")
'2008-03-08 21:20:40.516243'
>>> parsedate("next monday")
'2008-03-10 00:00:00'
>>> parsedate("10pm last week")
'2008-02-29 22:00:00'
>>> parsedate("last tuesday")
'2008-03-04 00:00:00'

Thanks to everyone who helped!

Jacob



More information about the Python-list mailing list