How to convert local time string to UTC?

后端 未结 23 1182
离开以前
离开以前 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 05:13

    For getting around day-light saving, etc.

    None of the above answers particularly helped me. The code below works for GMT.

    def get_utc_from_local(date_time, local_tz=None):
        assert date_time.__class__.__name__ == 'datetime'
        if local_tz is None:
            local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
        local_time = local_tz.normalize(local_tz.localize(date_time))
        return local_time.astimezone(pytz.utc)
    
    import pytz
    from datetime import datetime
    
    summer_11_am = datetime(2011, 7, 1, 11)
    get_utc_from_local(summer_11_am)
    >>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=)
    
    winter_11_am = datetime(2011, 11, 11, 11)
    get_utc_from_local(winter_11_am)
    >>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=)
    

提交回复
热议问题