加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:54:50 所属栏目:Python 来源:网络整理
导读:我在字符串中有日期: 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') 但我得到错误: ValueErro
我在字符串中有日期:

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 parser

In [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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读