如何将字符串日期与时区转换为datetime?

如何将字符串日期与时区转换为datetime?,第1张

概述我在字符串中有日期: Tue Oct 04 2016 12:13:00 GMT+0200 (CEST) 我使用(根据https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior): datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z') 我在字符串中有日期:

Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)

我使用(根据https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior):

datetime.strptime(datetime_string,'%a %b %m %Y %H:%M:%s %z %Z')

但我得到错误:

ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%s %z %Z'

怎么做正确?

解决方法 python datetime无法解析GMT部分(您可能希望以您的格式手动指定它).您可以使用dateutil代替:

In [16]: s = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'In [17]: from dateutil import parserIn [18]: parser.parse(s)Out[18]: d = datetime.datetime(2016,10,4,12,13,tzinfo=tzoffset(u'CEST',-7200))In [30]: d.utcoffset()Out[30]: datetime.timedelta(-1,79200)In [31]: d.tzname()Out[31]: 'CEST'
总结

以上是内存溢出为你收集整理的如何将字符串日期与时区转换为datetime?全部内容,希望文章能够帮你解决如何将字符串日期与时区转换为datetime?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1193753.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存