Python: Convert Dictionary of String Times to Date Times

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")

You can use a dictionary comprehension:

new_dict = {datetime.strptime(key, "%Y-%m-%d %H:%M:%S"): val for key, val in alerts['alert_date'].items()}

Also note that, since you are using datetime.strptime with an specified format it might raise a ValueError. Which in that case the dict-comprehension won't be helpful. So if you are not sure about the fromat of your dates you need to handle the exceptions:

new_dict = {}
for k, v in alerts['alert_date'].items():
    try:
        new_dict[datetime.strptime(k, "%Y-%m-%d %H:%M:%S")] = v 
    except ValueError:
        new_dict[datetime.strptime(k, "%Y-%m-%d %H:%M:%S")] = '' # or what you want