Kil*_*ick 5 python string django time dictionary
我有一本alerts[]
包含密钥的字典alert_date
.所有日期/时间都存储为字符串.我在Django中显示日期,但模板无法格式化存储为sting的时间.所以,我想在我的视图中将其转换为:
foo = "2014-10-07 00:00:00"
bar = datetime.strptime(foo, "%Y-%m-%d %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)
但是,我想立刻转换所有字典时间值.我通过API调用将字典作为JSON抓取.我想做这样的事情(这显然是无效的代码):
alerts = resp_data['alerts']
for v in alerts['alert_date']:
v = datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)
//编辑:JSON响应是一个包含的字典alerts
,它是一个字典列表,如下所示:
{"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",
}
]}
Run Code Online (Sandbox Code Playgroud)
您可以使用字典理解:
new_dict = {datetime.strptime(key, "%Y-%m-%d %H:%M:%S"): val for key, val in alerts['alert_date'].items()}
Run Code Online (Sandbox Code Playgroud)
另请注意,由于您使用的datetime.strptime
是指定格式,因此可能会引发ValueError
. 在这种情况下,听写理解不会有帮助。因此,如果您不确定日期的起始时间,则需要处理异常:
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
Run Code Online (Sandbox Code Playgroud)
编辑:
现在您已经添加了一些示例 json 响应数据,我知道这个答案是正确的,alerts
是一个 dicts 列表:
从你的例子中,我现在假设:
alerts
是alert
字典列表alert['alert_date']
是一个日期字符串因此,我建议您这样做:
alerts = resp_data['alerts']
for alert in alerts:
alert['alert_date'] = datetime.strptime(alert['alert_date'], "%Y-%m-%d %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)