【问题标题】:Datetime with timezone in PythonPython中带有时区的日期时间
【发布时间】:2020-06-28 02:13:32
【问题描述】:

我有一个字符串“Fri, 26 Jun 2020 20:47:07 BST”。我需要将字符串转换为 UTC 吗?

时区(BST、PST、MST、IST 等)因来源而异。所以代码应该能够识别时区并将其始终转换为 UTC...

【问题讨论】:

标签: python-3.x datetime


【解决方案1】:

如您所见,“BST”是时区的模糊缩写。使其明确的一种便捷方法是定义一个时区映射dict,您可以将其提供给dateutilparser

import dateutil

s = "Fri, 26 Jun 2020 20:47:07 BST"

tzmapping = {"BST": dateutil.tz.gettz('Europe/London')}

dtobj = dateutil.parser.parse(s, tzinfos=tzmapping)

print(dtobj)
# 2020-06-26 20:47:07+01:00

现在获取 UTC 和 UTC 一样简单

# to UTC:
dtobj_utc = dtobj.astimezone(dateutil.tz.UTC)    
print(dtobj_utc)
# 2020-06-26 19:47:07+00:00

【讨论】:

    【解决方案2】:
    from dateutil.tz import *
    from datetime import datetime
    import pytz
    
    # This contains the local timezone 
    local = tzlocal()
    now = datetime.now()
    now = now.replace(tzinfo = local)
    
    # prints a timezone aware datetime
    print now
    

    【讨论】:

    • 那是 Python 2.7 吗?你需要 pytz 做什么?为什么是明星进口?此外,问题与当地时间无关。
    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多