在 Python 中解析 rfc3339 日期字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23277268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:37:42  来源:igfitidea点击:

Parse rfc3339 date strings in Python?

pythondatedatetime-parsingrfc3339

提问by Spearfisher

I have a datasets where all the dates have the following format:

我有一个数据集,其中所有日期都具有以下格式:

2012-10-09T19:00:55Z

I'd like to be able to be able to use methods like .weekdayon them. How do I convert them to the proper format in Python?

我希望能够.weekday对它们使用类似的方法。如何在 Python 中将它们转换为正确的格式?

回答by Ffisegydd

You can use dateutil.parser.parseto parse strings into datetime objects.

您可以使用dateutil.parser.parse将字符串解析为日期时间对象。

dateutil.parser.parsewill attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptimewhich you supply a format string to (see Brent Washburne's answer).

dateutil.parser.parse将尝试猜测您的字符串的格式,如果您事先知道确切的格式,那么您可以使用datetime.strptime您提供格式字符串的格式(请参阅 Brent Washburne 的回答)。

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

回答by Brent Washburne

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

这已经在这里得到了回答:How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

回答by brunetton

You should have a look at momentwhich is a python port of the excellent js lib momentjs.

你应该看看moment哪个是优秀的 js lib 的 python 端口momentjs

One advantage of it is the support of ISO 8601strings formats, as well as a generic "% format" :

它的一个优点是支持ISO 8601字符串格式,以及通用的“% 格式”:

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

结果:

2012-10-09 19:10
2