在 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
Parse rfc3339 date strings in Python?
提问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 .weekday
on them. How do I convert them to the proper format in Python?
我希望能够.weekday
对它们使用类似的方法。如何在 Python 中将它们转换为正确的格式?
回答by Ffisegydd
You can use dateutil.parser.parse
to parse strings into datetime objects.
您可以使用dateutil.parser.parse
将字符串解析为日期时间对象。
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which 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 moment
which is a python port of the excellent js lib momentjs
.
你应该看看moment
哪个是优秀的 js lib 的 python 端口momentjs
。
One advantage of it is the support of ISO 8601
strings 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