Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
    }
]}
like image 373
Kilpatrick Avatar asked Apr 20 '16 19:04

Kilpatrick


1 Answers

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['alert_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")
like image 72
DevLounge Avatar answered Nov 14 '22 23:11

DevLounge