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",
}
]}
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
dictionariesalert['alert_date']
is a date stringTherefore 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")
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