I’ve started posting over at Django snippets, which is a great resource for finding useful bits of functionality. My first set of snippets is focused on datetime conversions.
FuzzyDateTimeField is a drop in replacement for the standard DateTimeField that uses dateutil.parser with
fuzzy=True to clean the value, allowing the parser to be more liberal with the input formats it accepts.
The isoutc template filter produces an ISO format UTC datetime string from a timezone aware datetime object.
The timeto template filter is a more compact version of django’s timeuntil filter that only shows hours & minutes, such as “1hr 30min”.
JSON encode ISO UTC datetime is a way to encode datetime objects as ISO strings just like the isoutc template filter.
JSON decode datetime is a simplejson object hook for converting the
datetime attribute of a JSON object to a python datetime object. This is especially useful if you have a list of objects that all have
datetime attributes that need to be decoded.
Imagine you’re making a time based search engine for movies and/or events. Because your data will span many timezones, you decide that all dates & times should be stored on the server as UTC. This pushes local timezone conversion to the client side, where it belongs, simplifying the server side data structures and search operations. You want your search engine to be AJAX enabled, but you don’t like XML because it’s so verbose, so you go with JSON for serialization. You also want users to be able to input their own range based queries without being forced to use specific datetime formats. Leaving out all the hard stuff, the above snippets can be used for communication between a django webapp and a time based search engine.