pd_to_datetime时间戳转换到本地时间

直接用pd_to_datetime显示的时间与本地时间差8小时

方法一

继续使用pd.to_datetime,使用orgin字段控制一下起始时间,暂没有找到优雅的直接控制时区的办法

data["date_orgin"] = pd.to_datetime(data["timestamp"],unit = "ms",origin = "1970-01-01 08:00:00")

如果碰到报错 dtype: object' is not compatible with origin='1970-01-01 08:00:00'; it must be numeric with a unit specified

这是因为时间格式不是数字,用pd.to_numeri函数转换下就可以了,代码如下

Dataframe['new_column']=pd.to_datetime(pd.to_numeric(Dataframe['column'],errors='coerce'),errors='coerce',origin='1899-12-30',unit='D')

方法二

使用apply方法加自己自定义一个函数

def stamp2time(timeStamp): #时间戳转日期函数
    """
    功能:将时间戳转换成日期函数 例如:1606708276268 ==》2020-11-30 11:51:16
    参数:timeStamp 时间戳,类型 double 例如:1606708276268
    返回值:日期, 类型:字符串 2020-11-30 11:51:16
    """
    time_local = time.localtime(timeStamp/1000)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    
    return dt
 
 
data['date_func'] = data["timestamp"].apply(stamp2time)

参考:

https://blog.csdn.net/zkyxgs518/article/details/120080526

https://stackoverflow.com/questions/42826388/using-time-zone-in-pandas-to-datetime

https://stackoverflow.com/questions/63753525/changing-a-column-to-datetime-format-with-specified-origin

posted @ 2022-06-22 14:11  C羽言  阅读(932)  评论(0)    收藏  举报