gpt4 book ai didi

python - 如何将带时区的字符串日期转换为日期时间?

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:28 24 4
gpt4 key购买 nike

我在字符串中有日期:

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'

如何正确操作?

最佳答案

%z 是+0200%ZCEST。因此:

>>> s = "Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)"
>>> datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=datetime.timezone(datetime.timedelta(0, 7200), 'CEST'))

我还用 %d 替换了你的 %m%m 是月份,以数字形式表示,因此在您的情况下,04 将被解析为四月。

关于python - 如何将带时区的字符串日期转换为日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39853321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com