Pandas日期时间列到Excel序列类型错误

plicqrtu  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(139)

我有一个列在我的dataframe有一堆日期与小时和分钟,我试图取代它或创建一个新的Excel的串行格式,并有它作为浮动做一些计算。
我尝试了很多方法,但仍然不能让它工作。不管我怎么尝试,我总是出错。我正在加载的源csv有一个名为df['dates']的列,它看起来像这样:

0       2022-02-23 09:30:00-05:00
1       2022-02-23 09:45:00-05:00
2       2022-02-23 10:00:00-05:00
3       2022-02-23 10:15:00-05:00
4       2022-02-23 10:30:00-05:00
                  ...            
7912    2023-04-25 10:45:00-04:00
7913    2023-04-25 11:00:00-04:00
7914    2023-04-25 11:15:00-04:00
7915    2023-04-25 11:30:00-04:00
7916    2023-04-25 11:45:00-04:00

下面是我的代码:

import pandas as pd

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

# convert datetime column to excel serial number format
excel_serial_dates = pd.to_datetime("1900-01-01") + pd.to_timedelta(df['dates'] - pd.Timestamp("1899-12-30"), unit='D')
df['excel_serial'] = pd.Series([x.to_pydatetime().timestamp() / 86400 + 25569 for x in excel_serial_dates])

# convert excel serial number column to float
df['excel_serial'] = df['excel_serial'].astype(float)

但是,它返回以下错误:

TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'Timestamp'

有什么建议吗?我知道一定有个简单的办法。
先谢谢你了。

gg0vcinb

gg0vcinb1#

好了,最后我意识到,当我从CSV加载文件时,Python将日期列识别为一个对象,它一直在抛出所有内容。以下是我如何解决的:

# Convert the 'datetime_column' to Pandas datetime format with UTC timezone
df['datetime_column'] = pd.to_datetime(df['dates'], utc=True)

# Convert timezone-aware datetime values to UTC timezone
df['datetime_column'] = df['datetime_column'].dt.tz_convert('UTC')

# Convert the Pandas datetime format to Excel serial format
excel_serial = (df['datetime_column'] - pd.Timestamp('1900-01-01', tz='UTC')) / pd.Timedelta('1 day')
excel_serial += ((df['datetime_column'].dt.hour * 3600 + df['datetime_column'].dt.minute * 60
                  + df['datetime_column'].dt.second) / 86400)

# Convert the resulting values to floats
excel_serial = excel_serial.astype('float64')

# Replace the original column with the transformed values
df['datetime_column'] = excel_serial
df

如果有人有一个更Python的方式来做到这一点,会很乐意看到它!非常感谢!

相关问题