jmquintana79
8/5/2016 - 7:44 AM

Datetime conversion between utc and local time

Datetime conversion between utc and local time


"""
Transform utc time system to local time
"""
def utc2local(dateutc):
    from datetime import datetime
    from dateutil import tz
    # setup
    from_zone = tz.tzutc()
    to_zone = tz.tzlocal()
    # transform
    try:
        # if dateutc is not a string is transformed previously
        utc = datetime.strptime(dateutc,"%Y-%m-%d %H:%M:%S")
    except:
        utc = dateutc
    utc = utc.replace(tzinfo=from_zone)
    datelocal = utc.astimezone(to_zone)
    # return datetime object
    return datetime(datelocal.year,datelocal.month,datelocal.day,datelocal.hour,datelocal.minute,datelocal.second)

        
"""
Transform utc time system to local time
"""
def local2utc(datelocal):
    from datetime import datetime
    from dateutil import tz
    # setup
    to_zone = tz.tzutc()
    from_zone = tz.tzlocal()
    # transform
    try:
        # if dateutc is not a string is transformed previously
        local = datetime.strptime(datelocal,"%Y-%m-%d %H:%M:%S")
    except:
        local = datelocal
    local = local.replace(tzinfo=from_zone)
    dateutc = local.astimezone(to_zone)
    # return datetime object
    return datetime(dateutc.year,dateutc.month,dateutc.day,dateutc.hour,dateutc.minute,dateutc.second)