Login

JSON encode ISO UTC datetime

Author:
japerk
Posted:
April 13, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

If you want to do your own JSON serialization of 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.

1
2
3
4
5
6
7
import datetime
from dateutil import tz

def encode_datetime(obj):
	if isinstance(obj, datetime.datetime):
		return obj.astimezone(tz.tzutc()).strftime('%Y-%m-%dT%H:%M:%SZ')
	raise TypeError(repr(o) + " is not JSON serializable")

More like this

  1. Form field with fixed value by roam 1 day, 14 hours ago
  2. New Snippet! by Antoliny0919 1 week, 1 day ago
  3. Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
  4. get_object_or_none by azwdevops 6 months, 2 weeks ago
  5. Mask sensitive data from logger by agusmakmun 8 months, 2 weeks ago

Comments

Please login first before commenting.