在Python中如何将字符串转换为带有时区的日期时间 - python

            
                    
将字符串转换为日期时间时出现值错误。任何人都可以帮助解决此问题。

>>> from datetime import datetime
>>> date_str = "2018-07-13T17:12:02-0500"
>>> t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")

Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")
File "C:\Python27\lib\_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'

>>> t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z")

Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z")
File "C:\Python27\lib\_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '2018-07-13T17:12:02-0500' does not match format '%Y- 
%m-%dT%H:%M:%S%Z'
>>>

我正在使用python版本2.7.14

参考方案

from datetime import datetime
iso_ts = '2012-11-01T04:16:13-04:00'
datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, 
tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python:检查是否存在维基百科文章 - python

我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…