How do I convert local time to UTC in Python?

How do I convert local time to UTC in Python?

Asked on November 12, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Use this code convert local time to UTC:

    def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)
    def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)
    

      For ex-If source is a datetime.datetime object t, call as:

    local_to_utc(t.timetuple())
    
    Answered on November 12, 2018.
    Add Comment

      Example of converting local time to UTC with Python, but includes localize():

    import pytz, datetime
    utc = pytz.utc
    fmt = '%Y-%m-%d %H:%M:%S'
    amsterdam = pytz.timezone('Europe/Amsterdam')
    dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
    am_dt = amsterdam.localize(dt)
    print am_dt.astimezone(utc).strftime(fmt)
    '2012-04-06 08:00:00'
    
    Answered on November 12, 2018.
    Add Comment

    Get the answer with python-dateutil method:

    from dateutil import tz
    def datetime_to_utc(date):
    
    """Returns date in UTC w/o tzinfo"""
    
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
    
    Answered on November 12, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.