Login

Snippets by japerk

Snippet List

JSON decode datetime

If you have JSON objects with `datetime` attributes that you want to decode to python [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) objects, you can use `decode_datetime` as a [simplejson](http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html) object hook. `simplejson.loads(s, object_hook=decode_datetime)`.

  • datetime
  • json
Read More

JSON encode ISO UTC datetime

If you want to do your own JSON serialization of [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) objects instead of using DjangoJSONEncoder, use `simplejson.dumps(o, default=encode_datetime)`. The `encode_datetime` method will convert the datetime object to UTC and output an ISO format string just like the [isoutc template filter](http://www.djangosnippets.org/snippets/1424/).

  • datetime
  • json
  • utc
Read More

timeto template filter

This is a more compact version of django's [timeuntil](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#timeuntil) filter that only shows hours & minutes. If used like `{{ dt|timeto }}`, will produce output like "1hr 30min". If you know for sure that the server has the same timezone as the [datetime](http://docs.python.org/library/datetime.html#datetime-objects) value, then you don't need [datetutil.tz](http://labix.org/python-dateutil#head-587bd3efc48f897f55c179abc520a34330ee0a62) for utc time conversion.

  • datetime
  • time
  • humanize
Read More

isoutc template filter

Use this template filter to produce an ISO format UTC datetime string from a [timezone aware](http://docs.python.org/library/datetime.html#datetime.tzinfo) [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) object. Usage example in a template: `<input name="when" type="hidden" value="{{ dt|isoutc }}"`. You must have [dateutil](http://labix.org/python-dateutil) installed for `tz.tzutc()` to work. And of course, you'll need to load it as a [custom tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) to use it. The output format differs from python's [datetime.isoformat](http://docs.python.org/library/datetime.html#datetime.datetime.isoformat) by ignoring the `microsecond` and including a "Z" suffix for the UTC timezone. For ease of use, it is also not double quoted as the standard suggests.

  • datetime
  • utc
Read More

FuzzyDateTimeField

FuzzyDateTimeField is a drop in replacement for the standard [DateTimeField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield) that uses [dateutil.parser](http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c) to clean the value. It has an extra keyword argument `fuzzy=True`, which allows it to be more liberal with the input formats it accepts. Set `fuzzy=False` for more strict validation.

  • datetime
  • humanize
Read More

japerk has posted 5 snippets.