utc时间转换为太平洋时间

方法一

from datetime import datetime
from pytz import timezone

cst_tz = timezone('Asia/Shanghai')
utc_tz = timezone('UTC')
pst_tz = timezone('America/Los_Angeles')

day = datetime.strptime('2020-12-11 20:00:00', '%Y-%m-%d %H:%M:%S')


aa = day.astimezone(tz=cst_tz).strftime('%Y-%m-%d %H:%M:%S')
bb = day.astimezone(tz=pst_tz).strftime('%Y-%m-%d %H:%M:%S')
cc = day.astimezone(tz=utc_tz).strftime('%Y-%m-%d %H:%M:%S')
print('北京时间:', aa)
print('太平洋时间:', bb)
print('utc时间:', cc)

方法二

import calendar
from datetime import datetime, date, timedelta

MARKETPLACES = {'US': 'NA',
                'CA': 'NA',
                'JP': 'FE',
                'AU': 'FE',
                'UK': 'EU',
                'FR': 'EU',
                'IT': 'EU',
                'ES': 'EU',
                'DE': 'EU',
                'AE': 'EU',
                }


def get_weekday(datetime_obj, week_day="monday"):
    """
    获取指定时间的当周的星期x
    :param datetime_obj: 时间
    :param week_day: 指定的星期x
    :return:
    """
    d = dict(zip(("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"),
                 range(7)))  # datetime 模块中,星期一到星期天对应数字 0 到 6
    delta_hour = timedelta(days=1)  # 改变幅度为 1 天
    while datetime_obj.weekday() != d.get(week_day):
        if datetime_obj.weekday() > d.get(week_day):
            datetime_obj -= delta_hour
        elif datetime_obj.weekday() < d.get(week_day):
            datetime_obj += delta_hour
        else:
            pass
    return datetime_obj


def get_month_weekday(year, month, n=1, w="sunday", h=0):
    """
    获取 year 年,month 月的的第n个星期w和倒数第n个星期w的日期
    :param year: 指定年份,
    :param month: 指定月份
    :param n: n个或者倒是n个
    :param w: 指定的星期w
    :param h: 指定的小时
    :return:
    """
    # 获取第一和最后一天
    d = dict(zip(("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"),
                 range(7)))  # datetime 模块中,星期一到星期天对应数字 0 到 6
    weekday, count_day = calendar.monthrange(year=year, month=month)  # 返回指定月份1号的星期几,和本月的总天数
    first_day = datetime(year=year, month=month, day=1, hour=h)  # <type 'datetime.datetime'>
    last_day = datetime(year=year, month=month, day=count_day, hour=h)

    if n > 0:
        n = abs(n)
        if first_day.weekday() > d.get(w):  # 说明本周的星期w在上个月
            datetime_obj = first_day + timedelta(weeks=1)
        else:
            datetime_obj = first_day
        datetime_obj += timedelta(weeks=n - 1)
        weekday_day = get_weekday(datetime_obj=datetime_obj, week_day=w)
    else:
        n = abs(n)
        if last_day.weekday() < d.get(w):  # 说明本周的星期w在下一个月
            datetime_obj = last_day - timedelta(weeks=1)
        else:
            datetime_obj = last_day
        datetime_obj -= timedelta(weeks=n - 1)
        weekday_day = get_weekday(datetime_obj=datetime_obj, week_day=w)

    return weekday_day


def is_dst(dt, region):
    """
    "UK","DE","FR","ES","IT" 夏令时 取3月份的最后一个周日凌晨两点和10月份的最后一个星期天的凌晨1点
    "US","AU","CA","MX" 夏令时 取3月份的第二个周日凌晨两点和10月份的第一个星期天的凌晨两点
    :param dt: utc时间
    :return:  True:夏令时,Fasle:冬令时
    """
    if not isinstance(dt, datetime):
        raise ValueError("dt需为dtatime类型")
    year = dt.year

    if region == ["UK", "DE", "FR", "ES", "IT"]:
        summer_start_month = 3
        summer_start_n = -1
        summer_start_w = "sunday"
        summer_start_h = 2

        summer_end_month = 10
        summer_end_n = -1
        summer_end_w = "sunday"
        summer_end_h = 1

    elif region == ["US", "AU", "CA", "MX"]:
        summer_start_month = 3
        summer_start_n = 2
        summer_start_w = "sunday"
        summer_start_h = 2

        summer_end_month = 10
        summer_end_n = 1
        summer_end_w = "sunday"
        summer_end_h = 2
    else:
        raise ValueError(f"不支持当前国家{region}")
    sum_start = get_month_weekday(year, summer_start_month, n=summer_start_n, w=summer_start_w, h=summer_start_h)
    sum_end = get_month_weekday(year, summer_end_month, n=summer_end_n, w=summer_end_w, h=summer_end_h)
    print(sum_start, sum_end)
    if sum_start <= dt <= sum_end:
        return True
    return False


def conversion_time(dt, region="US"):
    """

    :param dt:  utc时间
    :param region: 国家地区
    :return: 当地时间
    """

    if region in ["US", "AU", "CA", "MX"]:
        dt = dt + timedelta(hours=-7) if is_dst(dt, region) else dt + timedelta(hours=-8)
    elif region == "UK":
        dt = dt + timedelta(hours=1) if is_dst(dt, region) else dt
    elif region in ["DE", "FR", "ES", "IT"]:
        dt = dt + timedelta(hours=2) if is_dst(dt, region) else dt + timedelta(hours=1)
    elif region == "JP":
        dt = dt + timedelta(hours=9)
    elif region == "IN":
        dt = dt + timedelta(hours=5)
    elif region == "SG":
        dt = dt + timedelta(hours=8)
    else:
        raise ValueError(f"不支持当前国家{region}")

    return dt


if __name__ == '__main__':
    # t = datetime(year=2020,month=11,day=19,hour=16)
    t = datetime.utcnow()
    print(conversion_time(t, region="JP"))

posted @ 2020-12-09 18:10  rm-rf*  阅读(556)  评论(0编辑  收藏  举报