簡體   English   中英

ExcelWriter ValueError: Excel 將 df 保存到 Excel 時不支持帶時區的日期時間

[英]ExcelWriter ValueError: Excel does not support datetime with timezone when saving df to Excel

我在這個問題上已經有一段時間了。

我將作者設置如下:

writer = pd.ExcelWriter(arquivo+'.xlsx', engine = 'xlsxwriter', options = {'remove_timezone': True})
df.to_excel(writer, header = True, index = True)

此代碼位於 s function 內。問題是每次我運行代碼時,它都會從數據庫中獲取信息,其中包含兩列 datetime64[ns, UTC] object 和時區信息。 但是當保存到 Excel 的代碼運行時,我收到:

ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.

我已經嘗試過幾種方法,例如“dt.tz_convert”、replace(tzinfo=None) 以及我在這里和周圍找到的其他解決方案。

代碼在我的個人電腦上運行沒有問題,我的同事使用相同的機器規格可以運行代碼。 只有在我的機器上它沒有。 我已經重新安裝了 python 和所有軟件包,包括格式化機器什么都沒有,錯誤仍然存在。

xlrd v1.1.0

xlsxwriter v1.0.4

python 3.7.4

pandas v0.25.1

如果有人能對這個問題有所了解,我將不勝感激。

謝謝

你的時間戳是什么格式的?

我只是有一個類似的問題。

我試圖將數據框保存到 Excel。 但是我得到了:

錯誤代碼

我檢查了我的日期格式,格式為'2019-09-01T00:00:00.000Z'

這是來自pandas.to_datetime的時間戳pandas._libs.tslibs.timestamps.Timestamp

其中包括一個方法date()將日期轉換為 excel 可接受的格式"%Y-%m-%d"

所以我的代碼是這樣的:

#Pseudo
df['date'] = old_dates
df['date'] = df['date'].apply(lambda a: pd.to_datetime(a).date()) 
# .date() removes timezone

...df.to_excel etc.

這應該可以完成工作,在導出到 excel 之前從列中刪除時區(使用 tz_localize(None))。

# Check which columns have timezones datetime64[ns, UTC] 
df.dtypes

# Remove timezone from columns
df['date'] = df['date'].dt.tz_localize(None)

# Export to excel
df.to_excel('filename.xlsx')

我發現這種方式更容易,更有活力。 此解決方案您 select 列按類型並應用了所需的轉換。

date_columns = df.select_dtypes(include=['datetime64[ns, UTC]']).columns
for date_column in date_columns:
    df[date_column] = df[date_column].dt.date
    
df.to_excel('anbima_feed.xlsx',engine='xlsxwriter')

僅當您需要相應時區中沒有時間的日期時,接受的答案才有效。 如果您的時間以 UTC 為紀元,您需要將其轉換為 Striftime,然后再轉換為 Datetime 以保存時區中的時間。

參考: https://python-forum.io/thread-31300.html

示例:字段 ts 是 UTC 中的時間戳,以 Epoch 為單位,以毫秒為單位。

df['ts']
OUT:
0      1619801902867
1      1619765681594
2      1619712291984
3      1619680298648
4      1619629032109
5      1619593388626
6      1619531314509
7      1619509338368
8      1619449287828
9      1619433411243
10     1619103667781
11     1619078244871
12     1619021782951
13     1618990214111
14     1618931135540
15     1618903774632

然后您需要將其轉換為所需的時區:

df['ts'] = pd.to_datetime(df['ts'],unit='ms').dt.tz_localize('utc').dt.tz_convert('Europe/Vatican')
df['ts'] = df['ts'].apply(lambda a: datetime.datetime.strftime(a,"%Y-%m-%d %H:%M:%S"))
df['ts'] = pd.to_datetime(df['ts'])

結果將如下所示:

df['ts']
OUT:
0     2021-04-30 18:58:22
1     2021-04-30 08:54:41
2     2021-04-29 18:04:51
3     2021-04-29 09:11:38
4     2021-04-28 18:57:12
5     2021-04-28 09:03:08
6     2021-04-27 15:48:34
7     2021-04-27 09:42:18
8     2021-04-26 17:01:27
9     2021-04-26 12:36:51
10    2021-04-22 17:01:07
11    2021-04-22 09:57:24
12    2021-04-21 18:16:22
13    2021-04-21 09:30:14
14    2021-04-20 17:05:35
15    2021-04-20 09:29:34

在此之后,xlsxwriter 將接受它並寫入 excel 而不會出現錯誤消息。

Pandas中還有另一種使用UTC參數的方法

import pandas as pd
# Adjust time zone from columns
df['date'] = pd.to_datetime( df['date'], errors='coerce',utc=True)
# Export to excel
df.to_excel('filename.xlsx')

我遇到了同樣的問題,做了一些文檔搜索,找到了 pandas 的解決方案

以下更改( options={'remove_timezone': True} )對我有用。

exwriter = pd.ExcelWriter(fullpath, engine='xlsxwriter', options={'remove_timezone': True})

如果您對工作表中的值是字符串感到滿意,則可以使用以下代碼來轉換日期時間

date_columns = df.select_dtypes(include=['datetime64[ns, UTC]']).columns
for date_column in date_columns:
    df[date_column] = df[date_column].apply(str)

我有一個類似的問題。 就我而言,日期是索引。 如果其他人遇到這個問題(通常是股票/貨幣/加密貨幣價格數據),您可以使用以下內容:

df.index = df.index.tz_localize(None)
df.to_excel(path)

只需將列轉換為str

df['date'] = df['date'].astype(str)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM