【问题标题】:TypeError: Timestamp subtractionTypeError:时间戳减法
【发布时间】:2017-06-22 20:23:59
【问题描述】:

我有一个用来收集数据的脚本。我遇到了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()

【问题讨论】:

  • 哪一行抛出异常?
  • forecasted_data.to_excel(writer, sheet_name='Sheet1') 抛出异常
  • 如果打印startend,tz属性是否可见?
  • 您查看过github.com/pandas-dev/pandas/issues/7056 吗?可能会有所帮助。

标签: python python-2.7 pandas datetime-format python-datetime


【解决方案1】:

当我运行您的示例代码时,我在堆栈跟踪结束时收到来自 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 选项:

writer = pd.ExcelWriter('test' + '_PythonExport.xlsx',
                        engine='xlsxwriter',
                        options={'remove_timezone': True})

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

【讨论】:

  • 感谢您的建议。我更新了我的 writer 变量以传递“remove_timezone”选项,并将包更新为 0.9.5,但我仍然遇到相同的时间戳错误。
  • 如果您可以在计算中省略时区,或者进行调整,那么您就不必使用remove_timezone 选项。此外,请确保去除时区的 xlsx 文件中的结果符合您的预期。
  • 嗯,不幸的是,我从 pvlib 库中提取的数据是 tz 特定的。这很奇怪。我想知道我是否应该创建一个新列并将df 索引重置为新列。只是看起来更像是一个补丁而不是一个解决方案。
【解决方案2】:

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

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

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

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

注意:

要选择 Pandas datetimetz dtypes,请使用“datetimetz”(0.20.0 中的新功能) 或 'datetime64[ns, tz]'

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 2013-11-17
    • 1970-01-01
    • 2013-02-03
    • 2022-11-02
    • 2021-12-29
    • 2011-04-02
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多