处理 pandas.datetime 类型时的消息“忽略异常”

DrJ*_*uzo 3 python warnings exception python-3.x pandas

我有一个 xlsx 文件,其中一列包含格式为“01.01.1900 09:01:25”的日期。该文件受密码保护,因此我通过 win32com.client 库将其转换为数据帧。

这是代码:

import pandas as pd
import win32com.client

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.DisplayAlerts = False
xlwb = xlApp.Workbooks.Open(File, False, True, None, " ") #Open Workbook password " "
xlws = xlwb.Sheets("Sheet 1") #Open Sheet 1        

#Get table dimensions 
LastRow = xlws.Range("A1").CurrentRegion.Rows.Count
LastColumn = xlws.Range("A1").CurrentRegion.Columns.Count
header=list((xlws.Range(xlws.Cells(1, 1), xlws.Cells(1, LastColumn)).Value)[0])
content = list(xlws.Range(xlws.Cells(2, 1), xlws.Cells(LastRow, LastColumn)).Value)
#Get the dataframe
df=pd.DataFrame(data=content, columns=header)
print (df)
Run Code Online (Sandbox Code Playgroud)

我检查了一次导入的 dtype 是否已自动且正确地分配给该列的 datetime64。问题是,每当我尝试对该列的任何值执行任何操作时(只需打印或比较它),我都会收到一条消息:

  File "pandas\_libs\tslibs\timezones.pyx", line 227, in pandas._libs.tslibs.timezones.get_dst_info

AttributeError: 'NoneType' object has no attribute 'total_seconds'

Exception ignored in: 'pandas._libs.tslib._localize_tso'
Traceback (most recent call last):
  File "pandas\_libs\tslibs\timezones.pyx", line 227, in pandas._libs.tslibs.timezones.get_dst_info
AttributeError: 'NoneType' object has no attribute 'total_seconds'
Traceback (most recent call last):
Run Code Online (Sandbox Code Playgroud)

尽管如此,代码运行良好,但警告消息让我很恼火。

我可以对数据类型做些什么来避免该警告?

DrJ*_*uzo 6

这样打开excel,content变量是元组列表。

看看这些元组,有一个 TimeZoneInfo 将所有日期本地化为一种时区,在我的例子中是“GMT 标准时间”。

因此,一旦转换为数据帧,执行df.dtypes结果时不仅是“datetime64”而且是“datetime64 (UTC+0:00) Dublin, Edimburg, ...”

此时区设置仅在通过win32com.client. 如果您删除了密码,您可以打开它pandas.read_excel并发现没有为这些日期时间设置时区,并且不会出现上述警告。

不知道它发生的确切原因,但我有原始示例的解决方案。警告消失将 tz 数据库识别的时区设置为"UTC"None。就像是:

df["col_name"]=df["col_name"].dt.tz_convert(None)
Run Code Online (Sandbox Code Playgroud)

  • 这也是使用其他win32com依赖包如```adodbapi```时的解决方案 (2认同)