Python之时间函数

1、datetime转long

import datetime, time

def datetime_to_long(time_start: datetime):
    """
    datetime格式转long 毫秒
    :param time_start:
    :return:
    """
    return int(time.mktime(time_start.timetuple()) * 1000.0 + time_start.microsecond / 1000.0)
    time_start = datetime.datetime(2019, 1, 1, 8, 0)
    print(datetime_to_long(time_start))

2、UTC时间字符串转化为北京时间的datetime对象

from datetime import datetime,timezone

def utc_2_pk(utctime_str:str) -> datetime:
    '''UTC时间字符串转化为北京时间的datetime对象
    :参数 utctime_str:UTC时间字符串,格式为yyyy-m-d H
    '''
    # 构造出没有时区的datetime对象
    local_format = "%Y-%m-%d %H:%M:%S"
    naive_time = datetime.strptime(utctime_str, local_format)
    # 取出上述对象的年月日小时构造一个时区为utc的datetime对象
    utctime = datetime(naive_time.year,naive_time.month,naive_time.day,naive_time.hour,tzinfo=timezone('UTC'))
    # 把时区为utc的对象转化为时区为Asia/Shanghai的datetime对象
    pktime = utctime.astimezone(timezone('Asia/Shanghai'))
    return datetime.strptime(pktime.strftime(local_format), local_format)

你可能感兴趣的:(Python)