utc时间如何转换为本地时间?

转换方法:

from datetime import datetime, timedelta


def utc_to_local(utc_str, timezone=8):
    '''
    utc时间转本地时间
    :param utc_str: utc时间字符串
    :param timezone: 时区(默认东八区)
    :return:
    '''
    try:
        given_datetime = datetime.strptime(utc_str, '%Y-%m-%dT%H:%M:%SZ')
    except:
        given_datetime = datetime.strptime(utc_str, '%Y-%m-%dT%H:%M:%S.%fZ')
    local_datetime = given_datetime + timedelta(hours=timezone)
    return datetime.strftime(local_datetime, '%Y-%m-%d %H:%M:%S')


print(utc_to_local("2012-03-20T16:00:00Z"))  # 2012-03-21 00:00:00
print(utc_to_local("2020-03-21T17:49:42.319772Z"))  # 2020-03-22 01:49:42
posted @ 2022-12-10 19:36  eliwang  阅读(929)  评论(0编辑  收藏  举报