Login

JSON decode datetime

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

If you have JSON objects with datetime attributes that you want to decode to python datetime objects, you can use decode_datetime as a simplejson object hook. simplejson.loads(s, object_hook=decode_datetime).

1
2
3
4
5
6
7
8
9
import dateutil.parser

def decode_datetime(obj):
	if 'datetime' not in obj:
		return obj
	
	dt = dateutil.parser.parse(obj['datetime'])
	obj['datetime'] = dt
	return obj

More like this

  1. codigo alto nivel by MrRocklion 1 month, 1 week ago
  2. Load template from specific app by Krzysiek555 1 month, 4 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 2 months ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 months ago

Comments

schinckel (on August 5, 2010):

If you have datetime objects as "%Y-%m-%d %H:%M:%S", then you don't need to convert them. Django will allow for using these in queries, and saving to the database.

Same with date ("%Y-%m-%d") and time ("%H:%M:%S") objects.

#

Please login first before commenting.