将JSON日期字符串转换为Python日期时间 [英] Convert JSON date string to Python datetime

查看:388
本文介绍了将JSON日期字符串转换为Python日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将日期转换为JSON时,javascript会以以下格式保存日期:

When translating dates to JSON, javascript is saving dates in this format:

2012-05-29T19:30:03.283Z

但是,我不确定如何将其放入python datetime对象.我已经尝试过这些:

However, I am not sure how to get this into a python datetime object. I've tried these:

# Throws an error because the 'Z' isn't accounted for:
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f')

# Throws an error because '%Z' doesn't know what to do with the 'Z'
#  at the end of the string
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f%Z')

我相信javascript将字符串保存为官方ISO格式,因此似乎应该有一种方法可以让python的datetime.strptime()读取它?

I believe that javascript is saving the string in official ISO format, so it seems that there should be a way to get python's datetime.strptime() to read it?

推荐答案

尝试以下格式:

%Y-%m-%dT%H:%M:%S.%fZ

例如:

>>> datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)

日期中的Z仅表示应将其解释为UTC时间,因此忽略它不会造成任何信息丢失.您可以在这里找到此信息: http://www.w3.org/TR/NOTE-datetime

The Z in the date just means that it should be interpreted as a UTC time, so ignoring it won't cause any loss of information. You can find this information here: http://www.w3.org/TR/NOTE-datetime

这篇关于将JSON日期字符串转换为Python日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆