DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
Before serializing, do the following:
time = datetime.strftime(time, DATETIME_FORMAT)
Do the following after unserializing:
time = datetime.strptime(time, DATETIME_FORMAT)
Example:
>>> from datetime import datetime >>> DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' >>> time = datetime.now() >>> time datetime.datetime(2011, 5, 5, 3, 1, 45, 646302) >>> time = time.strftime(DATETIME_FORMAT) >>> time '2011-05-05 03:01:45' >>> import json >>> time = json.loads(json.dumps(time)) >>> time '2011-05-05 03:01:45' >>> time = datetime.strptime(time, DATETIME_FORMAT) >>> time datetime.datetime(2011, 5, 5, 3, 1, 45)
If you find this to be somewhat inelegant, you might consider a custom json encoder / decoder. I personally tried the ones that were in the json package by default, but refused to stretch my hair with cryptic error messages. If you go this way, I can recommend a third-party json package.
source share