You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Pandas对LDAP时间戳进行舍入处理

解决Pandas读取18位LDAP时间戳精度丢失的问题

问题核心是18位整数超过了float64的精确表示范围,Pandas默认将大整数识别为float64类型,导致存储时被舍入,最终时间转换结果不准确。

解决方案

方法1:读取时指定列为字符串,再转为int64

读取CSV时强制Clock-Time列为字符串类型,避免被自动转为float64,之后再转换为int64(int64可精确存储9e18以内的整数,完全覆盖18位LDAP时间戳):

#!/usr/bin/python

from datetime import datetime, timedelta
import pandas

pandas.set_option('display.max_colwidth', None)
pandas.set_option('display.float_format','{:.0f}'.format)
pandas.set_option('display.precision', 20)

in_csv = "data.csv"

# 读取时指定Clock-Time为字符串类型
df = pandas.read_csv(in_csv, sep=',', header=0, dtype={'Clock-Time': str})
# 转换为int64类型
df['Clock-Time'] = df['Clock-Time'].astype('int64')

print(df.dtypes)
print(df)

# 矢量化转换时间戳(比apply效率更高)
df['Clock-Time'] = datetime(1601, 1, 1) + pandas.to_timedelta(df['Clock-Time'], unit='100ns')

print(df)

方法2:直接指定列为int64类型

如果CSV中Clock-Time列没有非整数值,可以直接在读取时指定dtype为int64:

df = pandas.read_csv(in_csv, sep=',', header=0, dtype={'Clock-Time': 'int64'})

效果验证

修改后输出的Clock-Time会保留原始精确值,转换后的时间也会区分不同的毫秒级差异:

Event ID         int64
Clock-Time       int64
ProcessID        int64
Size             int64
dtype: object
   Event ID         Clock-Time  ProcessID  Size
0        10 133081599160584000       2824    44
1        10 133081599160584000       2824    84
2        10 133081599160667000       2824    44
3        10 133081599160667000       2824    92
4        10 133081599160667000       2824   116
5        10 133081599160667000       2824   132
    Event ID          Clock-Time  ProcessID  Size
0        10 2022-09-21 02:11:56.058400       2824    44
1        10 2022-09-21 02:11:56.058400       2824    84
2        10 2022-09-21 02:11:56.066700       2824    44
3        10 2022-09-21 02:11:56.066700       2824    92
4        10 2022-09-21 02:11:56.066700       2824   116
5        10 2022-09-21 02:11:56.066700       2824   132

内容的提问来源于stack exchange,提问作者jjblack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:10:23