简体   繁体   English

将值设置为数据框时,熊猫会更改日期时间

[英]Pandas changes datetime when setting value to dataframe

When I use iloc to set a datetime value to a dataframe cell, the value is changed当我使用 iloc 将日期时间值设置为数据帧单元格时,该值已更改

import datetime as dt
import pandas as pd

t = '2019-12-29 13:17:34.678000'
t = dt.datetime.fromisoformat(t)
print(t)
# 2019-12-29 13:17:34.678000

df = pd.DataFrame({'t': [t]})
print(df)
#                         t
# 0 2019-12-29 13:17:34.678

df.iloc[0, df.columns.get_loc('t')] = t
print(df)
#                               t
# 0 2019-12-29 13:17:34.678000128

Why is this happening and how can I prevent it?为什么会发生这种情况,我该如何预防?

You can apply function isoformat that will trunc time to milliseconds removing microsecond precision:您可以应用函数isoformat将时间缩短到毫秒,从而消除微秒精度:

t = dt.datetime.fromisoformat(t).isoformat(timespec='milliseconds')

For details regarding isoformat, please follow: https://docs.python.org/3/library/datetime.html#datetime.time.microsecond有关 isoformat 的详细信息,请关注: https : //docs.python.org/3/library/datetime.html#datetime.time.microsecond

Please note that as documentation says, excluded time components are truncated, not rounded.请注意,正如文档所说,排除的时间分量被截断,而不是四舍五入。

This seems to be a bug in pandas 0.25.2 .这似乎是 pandas 0.25.2一个错误。 It doesn't happen in the latest version, 1.0.1 .它不会发生在最新版本1.0.1

In 0.25.2 it can be worked around by using .at instead of .iloc0.25.2可以通过使用工作围绕.at代替.iloc

t = '2019-12-29 13:17:34.678000'
t = dt.datetime.fromisoformat(t)
print(t)
# 2019-12-29 13:17:34.678000

df = pd.DataFrame({'t': [t]})
print(df)
#                         t
# 0 2019-12-29 13:17:34.678

df.at[0, 't'] = t
print(df)
#                         t
# 0 2019-12-29 13:17:34.678

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM