将JSON日期字符串转换为python datetime [英] Converting JSON date string to python datetime

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

问题描述

将日期翻译成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 datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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