【问题标题】:Convert Time to UTC Using GMT Offset使用 GMT 偏移量将时间转换为 UTC
【发布时间】:2012-05-01 11:53:50
【问题描述】:

我有以下格式的日期时间和 UTC 偏移量。

22-01-2012 22:01:30 +0530

12-02-2012 13:00:34 -0400

如何使用 Python 中的 pytz 模块将其转换为 UTC?

【问题讨论】:

    标签: python time utc


    【解决方案1】:

    python3:

    >>> import time
    >>> from datetime import datetime
    >>> tm = '22-01-2012 22:01:30 +0530'
    >>> fmt = '%d-%m-%Y %H:%M:%S %z'
    >>> time.asctime(datetime.strptime(tm, fmt).utctimetuple())
    'Sun Jan 22 16:31:30 2012'
    

    【讨论】:

    • 嗨 Kev,感谢解决方案,它在 python 3 中运行良好,但似乎不适用于 python 2.x,python 2.x 中是否有等价物?
    【解决方案2】:

    我会使用来自http://labix.org/python-dateutil#head-2f49784d6b27bae60cde1cff6a535663cf87497b 的 dateutil.parser。确保为您的 python 版本使用正确的版本。

    import datetime
    import dateutil.parser
    import pytz
    loc_dt = dateutil.parser.parse('22-01-2012 22:01:30 +0530')
    loc_dt.astimezone(pytz.utc)
    

    【讨论】:

    • 非常感谢,这很有帮助
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多