I have...
entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())})
How do I convert the datetime (that was converted to unicode) back to datetime again?
So that I can do something like...
entity2 = simplejson.loads(entity)
#your answer here..
add5 = entity2["a"] + datetime.timedelta(minutes=5)
Thanks!
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
Do the following before serializing:
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)
In case you find this somewhat inelegant, you might consider a custom json encoder/decoder. I personally have tried the ones in the default json package, but gave up pulling my hair out with cryptic error messages. If you go this path, I might recommend a third party json package.
Use datetime.datetime.strptime.
dt = datetime.datetime.strptime(entity2['a'], '%Y-%m-%d %H:%M:%S.%f')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With