如何将"Tue Feb 25 2014 00:00:00 GMT+0530 (IST)"转换为python datetime对象?
我对这个日期格式 Tue Feb 25 2014 00:00:00 GMT+0530 (IST)
有一些疑问。
Tue Feb 25 2014 00:00:00
是指GMT
还是IST
呢?- 这个日期能转换成 Python 的
datetime
吗? - 还有,能把它转换成
DD-MM-YY,HH:MM:SS
的格式,并且是 GMT 时区吗?
这是我尝试转换成 python datetime
的代码:
但是当我用 %z
时出现了错误:
>>> time_format="%a %b %d %Y %H:%M:%S GMT%z (%Z)"
>>> v="Tue Feb 25 2014 00:00:00 GMT+0530 (IST)"
>>> mydate=datetime.strptime(v,time_format)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
不过这个方法是可以的:
>>> time_format="%a %b %d %Y %H:%M:%S GMT (%Z)"
>>> v="Tue Feb 25 2014 00:00:00 GMT (IST)"
>>> datetime.strptime(v,time_format)
datetime.datetime(2014, 2, 25, 0, 0)
但我还是对 TIMEZONE
的概念不太理解。
2 个回答
2
我觉得最好的办法是试试这样的做法,特别是如果你想在 Python 3.6.9 中避免使用外部库的话:
datetime.strptime(v,"%a %b %d %Y %H:%M:%S %Z%z (IST)")
5
在系统终端中
easy_install python-dateutil
在Python的命令行中
from dateutil import parser as date_parser
print date_parser.parse("Tue Feb 25 2014 00:00:00 GMT+0530 (IST)")
dateutil库里的parse功能通常可以把你给它的任何东西都转换成Python的日期时间格式。