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 @   C羽言  阅读(795)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示