gpt4 book ai didi

python - 将 ns 精度的字符串转换为 Pandas 数据框中的日期时间

转载 作者:行者123 更新时间:2023-11-28 17:24:31 25 4
gpt4 key购买 nike

我很难将 ns 精度的字符串转换为 Pandas 数据帧中的日期时间格式。

我有一个如下所示的数据框:

print df
Event Time
0 A 08:00:00.123456789
1 B 08:00:00.234567890
2 C 08:00:00.345678901

我想在不丢失 ns 精度的情况下将时间列从字符串转换为日期时间。我试过以下:

df['Time'] = pd.to_datetime(df['Time'])

但是当我打印 df 时,我发现我只有 us 精度。

df['时间'] = df['时间'].astype('datetime64[ns]')

但是这里我得到一个错误,比如

"Error parsing datetime string "08:00:00.345678901" at position 2"

最佳答案

以下对我有用:

>>> df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f')
>>> df
Event Time
0 A 1900-01-01 08:00:00.123456789
1 B 1900-01-01 08:00:00.234567890
2 C 1900-01-01 08:00:00.345678901

documentation for pd.to_datetime 中关于 format 参数的说明:

strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds.

关于python - 将 ns 精度的字符串转换为 Pandas 数据框中的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39897698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com