Source

appengine_form_utils / human_date_time_field.py

"""

HumanDateTime: when you want to provide a field that lets your users input dates like "yesterday".

Uses parsedatetime to do this. Assumes that parsedatetime lives in a module called vendor.

Based off the patch at: <http://code.djangoproject.com/ticket/3113>, with mods to
get it working on appengine

"""

import datetime
from google.appengine.ext.db import djangoforms

### HumanDateTimeField ###
from vendor.parsedatetime import parsedatetime

#The constructor compiles a bunch of regexs, might as well do it only once.
parse_calendar = parsedatetime.Calendar()

def parse_date_time(string):
    # parsedatetime seems to have a bug in it where MM-DD-YY(YY) dates are not accepted, and return the current date.
    # this might be proper for some usages (although I don't know what), but is not proper when you're
    # trying to feed a date into this picker
    # So, do a find and replace on and - and change them to /s.
    # This shouldn't cause other problems, but it is possible. WD-rpw 02-19-2011
    string = string.replace("-", "/")

    tup, flag = parse_calendar.parse(string)
    if (flag == 0):     # The string could not be parsed
        raise ValueError, "Unable to parse date/time."
    if (flag == 1):     # This was just a date
        value = datetime.datetime(*(tup[:3])) 
    else:
        value = datetime.datetime(*(tup[:6]))
    return value

class HumanDateTimeField(djangoforms.forms.Field):
    """
    Uses the parsedatetime library to clean the value thereby allowing
    many different date-formats, including human readable strings like,
    "tomorrow" and "thursday at 10 pm".
    
    parsedatetime library: http://cheeseshop.python.org/pypi/parsedatetime/
    """
    
    def clean(self, value):
        """
        Validates that the input can be converted to a datetime. Returns a Python
        datetime.datetime object.
        """
        
        super(HumanDateTimeField, self).clean(value)
        if value in (None, ''):
            return None
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)
        try:
            return parse_date_time(value)
        except ValueError:
            pass
        raise djangoforms.forms.ValidationError(
            u'Enter a valid date/time, like "today", "next tuesday at 2 am", "2006-10-28", or "10/24/99"')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.