python utc和当地时间之间的日期时间转换

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python utc和当地时间之间的日期时间转换相关的知识,希望对你有一定的参考价值。


"""
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)

以上是关于python utc和当地时间之间的日期时间转换的主要内容,如果未能解决你的问题,请参考以下文章

Python pytz:将本地时间转换为 UTC。本地化似乎没有转换

电子邮件“日期”标题应该是发件人的当地时间还是 UTC?

Js 怎么把UTC时间到转换到当地时间

我从当地时间到 UTC 的转换有啥问题

UTC 到夏令时的当地时间

使用时区城市坐标和当地时间进行时区转换[重复]