[英]Pandas datetime values messed up after saving df to excel and then reading back into a df
jan_21=[datetime(2021,1,1) + timedelta(hours=i) for i in range(5)]
jan_21
[datetime.datetime(2021, 1, 1, 0, 0),
datetime.datetime(2021, 1, 1, 1, 0),
datetime.datetime(2021, 1, 1, 2, 0),
datetime.datetime(2021, 1, 1, 3, 0),
datetime.datetime(2021, 1, 1, 4, 0)]
prices = np.random.randint(1,100,size=(5,))
prices
[46 23 13 26 52]
df = pd.DataFrame({'datetime':jan_21, 'price':prices})
df
datetime price
0 2021-01-01 00:00:00 83
1 2021-01-01 01:00:00 60
2 2021-01-01 02:00:00 29
3 2021-01-01 03:00:00 97
4 2021-01-01 04:00:00 67
到目前为止一切都很好,这就是我期望显示数据框和日期时间值的方式。 当我将数据帧保存到 excel 文件然后将其读回数据帧时,问题就出现了,日期时间值被弄乱了。
df.to_excel('price_data.xlsx', index=False)
new_df = pd.read_excel('price_data.xlsx')
new_df
datetime price
0 2021-01-01 00:00:00.000000 83
1 2021-01-01 00:59:59.999999 60
2 2021-01-01 02:00:00.000001 29
3 2021-01-01 03:00:00.000000 97
4 2021-01-01 03:59:59.999999 67
我希望df == new_df
评估为True
在问题的可能原因的背景下(参见 sophros 的回答),你可以做些什么来 - 表面上 - 规避问题是在生成 excel 文件之前将df["datetime"]
的单元格转换为字符串,然后转换在创建new_df
后,再次将字符串转换为日期时间:
df["datetime"] = df["datetime"].dt.strftime("%m/%d/%Y, %H:%M:%S")
df.to_excel('price_data.xlsx', index=False)
new_df = pd.read_excel('price_data.xlsx')
new_df["datetime"] = pd.to_datetime(new_df["datetime"], format="%m/%d/%Y, %H:%M:%S")
00:59:59.999999
和02:00:00.000001
和03:59:59.999999
时间部分差异的原因很可能与Excel和Python或pandas中日期/时间类型的二进制表示略有不同。
时间通常存储为浮点数,但不同之处在于时间是第 0 次(例如,第 1 AC 年或 1970 年 - 如在 Linux 中;这里有很好的解释)。 因此,转换可能会丢失日期/时间的一些最不重要的部分,并且您无能为力,只能将其四舍五入或使用与任何 float 类似的近似比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.