Natural Language Date Replacements

August 22, 2011 by Gabe | [mmd] |

Brett Terpstra just posted a very nice tool for inserting dates using Natural Language. His post is definitely worth a read.


Given my preference for Python and my previous experience with Natural Language Processing, I decided to implement something similar through a Keyboard Maestro trigger.

I have a macro that pops up a text box and asks for the date language you would like to interpret. Apparently KBM does have a leg up on TextExpander, in that it can accept input to a shell script or applescript. KBM truly is a fantastic tool.

I ended up with a really easy workflow that seems to work everywhere.

Step 1.

If I type "ndate" I get a pop-up:

NLP Popup

Step 2.

I type a string and hit return.

There is no step 3.

I then get the string "2011-09-02 09:00:00" dropped in as a replacement.


Here's the macro design:

NLP Macro


Here's the shell script (mostly python) that does all of the work. Don't forget the hash-bang at the beginning.


#!/usr/bin/env python
import os
import sys
import re
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import datetime

# Define Globals
pyDate = os.getenv('KMVAR_myDate')

# Function for parsing a string and returning a datetime value
def datetimeFromString( s ):
    c = pdc.Constants()
    p = pdt.Calendar(c)
    result, what = p.parse( s )
    dt = 0
    # See:
    # what was returned (see
    # 0 = failed to parse
    # 1 = date (with current time, as a struct_time)
    # 2 = time (with current date, as a struct_time)
    # 3 = datetime
    if what in (1,2,3):
        # result is struct_time
        dt = datetime.datetime( *result[:6] )
    if what == 0:
        # Failed to parse
        raise ValueError, ("Don't understand date '"+s+"'")
        dt = "Unrecognized Date"
    return dt
NLPDate = datetimeFromString(pyDate)
print NLPDate
blog comments powered by Disqus