How to convert local time string to UTC?

后端 未结 23 1595
离开以前
离开以前 2020-11-22 04:18

How do I convert a datetime string in local time to a string in UTC time?

I\'m sure I\'ve done this before, but can\'t find it and SO will hopefull

23条回答
  •  無奈伤痛
    2020-11-22 04:52

    Simple

    I did it like this:

    >>> utc_delta = datetime.utcnow()-datetime.now()
    >>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
    >>> print(utc_time)
    2008-09-17 19:01:59.999996
    

    Fancy Implementation

    If you want to get fancy, you can turn this into a functor:

    class to_utc():
        utc_delta = datetime.utcnow() - datetime.now()
    
        def __call__(cls, t):
            return t + cls.utc_delta
    

    Result:

    >>> utc_converter = to_utc()
    >>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
    2008-09-17 19:01:59.999996
    

提交回复
热议问题