Kilpatrick Kilpatrick - 7 months ago 8
Python Question

Python: Convert Dictionary of String Times to Date Times

I have a dictionary

alerts[]
which includes the key
alert_date
. All dates/times are stored as strings. I am displaying the date in Django, but templates can't format time stored as a sting. So, I want to convert it in my view as such:

foo = "2014-10-07 00:00:00"
bar = datetime.strptime(foo, "%Y-%m-%d %H:%M:%S")


But, I want to convert all the dictionary time values at once. I'm grabbing the dictionary as JSON through an API call. I want to do something like this (which is obviously invalid code):

alerts = resp_data['alerts']
for v in alerts['alert_date']:
v = datetime.strptime(v, "%Y-%m-%d %H:%M:%S")


//EDIT:
The JSON response is a dictionary which contains
alerts
, which is a list of dictionaries as follows:

{"alerts": [
{
"key1": "value11",
"key2": "value12",
"key3": "value13",
"alert_date": "2014-06-05 01:00:23.633000",
},
{
"key1": "value21",
"key2": "value22",
"key3": "value23",
"alert_date": "2010-12-31 00:00:00",
}
]}

Answer

EDIT: now that you have added some sample json response data, I know that this answer is correct, alerts IS a list of dicts:

From your example, I now assume that:

  • alerts is a list of alert dictionaries
  • alert['alter_date'] is a date string

Therefore I would suggest you to do:

alerts = resp_data['alerts']
for alert in alerts:
    alert['alert_date'] = datetime.strptime(alert['alert_date'], "%Y-%m-%d %H:%M:%S")