Python - 将日期的字符串表示形式转换为 ISO 8601
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4460698/
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
Python - Convert string representation of date to ISO 8601
提问by Alon Gubkin
In Python, how can I convert a string like this:
在 Python 中,我如何转换这样的字符串:
Thu, 16 Dec 2010 12:14:05 +0000
2010 年 12 月 16 日星期四 12:14:05 +0000
to ISO 8601 format, while keeping the timezone?
到 ISO 8601 格式,同时保留时区?
Please note that the orginal date is string, and the output should be string too, not datetimeor something like that.
请注意原始日期是字符串,输出也应该是字符串,而不是datetime类似的东西。
I have no problem to use third parties libraries, though.
不过,我使用第三方库没有问题。
采纳答案by unutbu
回答by Sumit Kumar
Python inbuilt datetimepackage has build in method to convert a datetime object to isoformat. Here is a example:
Python 内置的datetime包具有将 datetime 对象转换为 isoformat 的内置方法。下面是一个例子:
>>>from datetime import datetime
>>>date = datetime.strptime('Thu, 16 Dec 2010 12:14:05', '%a, %d %b %Y %H:%M:%S')
>>>date.isoformat()
output is
输出是
'2010-12-16T12:14:05'
I wrote this answer primarily for people, who work in UTC and doesn't need to worry about time-zones. You can strip off last 6 characters to get that string.
我主要为那些在 UTC 工作并且不需要担心时区的人写这个答案。您可以去掉最后 6 个字符以获得该字符串。
Python 2 doesn't have very good internal library support for timezones, for more details and solution you can refer to this answeron stackoverflow, which mentions usage of 3rd party libraries similar to accepted answer.
Python 2 对时区没有很好的内部库支持,有关更多详细信息和解决方案,您可以参考stackoverflow上的这个答案,其中提到了类似于已接受答案的 3rd 方库的使用。

