vn.py量化社区
By Traders, For Traders.
Member
avatar
加入于:
帖子: 169
声望: 36
import pandas as pd
from typing import Callable, Dict,List, Union
from pytz import timezone
TZ_INFO = timezone("Asia/Shanghai")   #使用东八区时区
#------------------------------------------------------------------------------------
def utc_to_local(timestamp:Union[str, float,int]):
    """
    把timestamp或者str的datetime转化成东八区的datetime
    """
    if isinstance(timestamp,str):
        if "Z" in timestamp:
            if "." in timestamp:
                local_time = pd.to_datetime(timestamp,format="%Y-%m-%dT%H:%M:%S.%fZ") + timedelta(hours=8)
            else:
                local_time = pd.to_datetime(timestamp,format="%Y-%m-%dT%H:%M:%SZ") + timedelta(hours=8)
        elif "T" in timestamp:
            if "." in timestamp:
                local_time = pd.to_datetime(timestamp,format="%Y-%m-%dT%H:%M:%S.%f") + timedelta(hours=8)
            else:
                local_time = pd.to_datetime(timestamp,format="%Y-%m-%dT%H:%M:%S") + timedelta(hours=8)
    elif isinstance(timestamp,float):
        local_time = pd.to_datetime(timestamp,unit = "s")   + timedelta(hours=8)
    elif isinstance(timestamp,int):
        #秒时间戳
        if len(str(timestamp)) == 10:
            local_time = pd.to_datetime(timestamp,unit = "s")   + timedelta(hours=8)
        #毫秒时间戳
        elif len(str(timestamp)) == 13:
            local_time = pd.to_datetime(timestamp,unit = "ms")   + timedelta(hours=8)
        #微妙时间戳
        elif len(str(timestamp)) == 16:
            local_time = pd.to_datetime(timestamp,unit = "us")   + timedelta(hours=8)
        #纳秒时间戳
        elif len(str(timestamp)) == 19:
            local_time = pd.to_datetime(timestamp,unit = "ns")   + timedelta(hours=8)
    return local_time.tz_localize(TZ_INFO)  #pandas timestamp添加时区
Member
avatar
加入于:
帖子: 9
声望: 0

大佬,请问这个关于时区方面的功能函数,看上去比较高大上,但是如何调用呢,方便给出一个命令行,

调用该函数包括函数参数列表(特别是函数的参数列表比较复杂:timestamp:Union[str, float,int])的例子吗,

好让我们多多参考哦,多谢啦!

Member
avatar
加入于:
帖子: 169
声望: 36

@泼奇 我是用在数字货币里面,该函数适用于交易所传入0时区的datetime需要统一到东八区时间,举个例子:
huobif里面收到委托回报的order_datetime可以这样写

order_datetime = utc_to_local(data["created_at"] / 1000)(这里不除1000也是可以转换的)
© 2015-2019 上海韦纳软件科技有限公司
备案服务号:沪ICP备18006526号-3