如何处理datetime64[ns]中的微/纳秒并转换为易读格式?
如何将pandas中的纳秒级时间列转换为更易读的格式?
你导入.xls文件后得到的时间列数据如下:
0 2022-09-27 11:56:22.733740 1 2022-09-27 11:56:22.733940 2 2022-09-27 11:56:22.734140 3 2022-09-27 11:56:22.734340 4 2022-09-27 11:56:22.734540 4995 2022-09-27 11:56:23.732740 4996 2022-09-27 11:56:23.732940 4997 2022-09-27 11:56:23.733140 4998 2022-09-27 11:56:23.733340 4999 2022-09-27 11:56:23.733540 Name: time, Length: 5000, dtype: datetime64[ns]
小数点后为纳秒值,以下几种方法可以将其转换为更易读的格式:
方法1:格式化字符串(保留指定精度)
使用dt.strftime将datetime对象转换为自定义格式的字符串,可按需保留毫秒(3位小数)或其他精度:
# 保留毫秒(3位小数) df['time_readable'] = df['time'].dt.strftime('%Y-%m-%d %H:%M:%S.%f').str[:-3] # 不保留小数(仅时分秒) df['time_readable'] = df['time'].dt.strftime('%Y-%m-%d %H:%M:%S')
转换后结果示例:2022-09-27 11:56:22.733(毫秒精度)或2022-09-27 11:56:22(无小数)。
方法2:修改数据类型(降低精度)
如果不需要纳秒级精度,可直接将列转换为datetime64[ms](毫秒)或datetime64[s](秒)类型,自动截断多余精度:
# 转换为毫秒精度 df['time'] = df['time'].astype('datetime64[ms]') # 转换为秒精度 df['time'] = df['time'].astype('datetime64[s]')
转换后数据类型变为对应精度的datetime格式,显示时会自动省略末尾冗余的零,更简洁。
方法3:仅修改显示格式(不改变原始数据)
如果不想修改原始数据类型,仅调整当前显示效果,可使用pandas的样式功能:
display(df.style.format({'time': lambda t: t.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}))
这种方式仅在当前会话的显示中生效,原始数据仍保留完整的纳秒精度。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

