类型错误:时间戳减法

2024-10-01 07:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本去收集数据。我遇到了TypeError: Timestamp subtraction must have the same timezones or no timezones错误。我已经看过其他关于这个错误的帖子,但是很难找到解决办法。在

如何绕过此错误。一旦收集到数据,我就不会对其进行操作,而且我不太明白为什么我不能将此dataframe保存到excel文档中。有人能帮忙吗?在

import pandas as pd
import numpy as np
import os
import datetime
import pvlib
from pvlib.forecast import GFS, NAM

#directories and filepaths
barnwell_dir = r'D:\Saurabh\Production Forecasting\Machine Learning\Sites\Barnwell'
barnwell_training = r'8760_barnwell.xlsx'

#constants
writer = pd.ExcelWriter('test' + '_PythonExport.xlsx', engine='xlsxwriter')    
time_zone = 'Etc/GMT+5'
barnwell_list = [r'8760_barnwell.xlsx', 33.2376, -81.3510] 

def get_gfs_processed_data1():
    start = pd.Timestamp(datetime.date.today(), tz=time_zone) #used for testing last week
    end = start + pd.Timedelta(days=6)
    gfs = GFS(resolution='quarter')
    #get processed data for lat/long point
    forecasted_data = gfs.get_processed_data(barnwell_list[1], barnwell_list[2], start, end)
    forecasted_data.to_excel(writer, sheet_name='Sheet1')


get_gfs_processed_data1()

Tags: 数据importdataget错误xlsxexcelstart
2条回答

当我运行示例代码时,在stacktrace的末尾收到XlsxWriter的以下警告:

"Excel doesn't support timezones in datetimes. "
TypeError: Excel doesn't support timezones in datetimes. 
Set the tzinfo in the datetime/time object to None or use the
'remove_timezone' Workbook() option

我认为这是不言自明的。要从时间戳中剥离时区,请按建议传递remove_timezone选项:

^{pr2}$

当我进行此更改时,示例运行并生成xlsx文件。注意,remove_timezone选项需要XlsxWriter>;=0.9.5。在

您可以像这样从所有datetime列中删除时区:

for col in df.select_dtypes(['datetimetz']).columns:
    df[col] = df[col].dt.tz_convert(None)

df.to_excel('test' + '_PythonExport.xlsx')

在那之后,你保存excel没有任何问题

注:

To select Pandas datetimetz dtypes, use 'datetimetz' (new in 0.20.0) or 'datetime64[ns, tz]'

相关问题 更多 >