必须为整数(时间戳记类型)

问题描述 投票:0回答:1
import pandas as pd
import datetime as dt
def abc():
    a=pd.read_excel('date time.xlsx')
    b=dt.date.today()
    print(b)
    c=(a['date of issue'])
    h=(c[0])
    f=dt.datetime(h)
    d=b-f
    print(d)

abc()它在7中显示错误,它需要读取一个整数(类型为Timestamp)

python-3.x
1个回答
0
投票
datetime模块是Python标准库的一部分。 datetime.datetime类的构造函数采用特定的年,月和日作为参数(Reference)。您将调用它例如用datetime.datetime(2020, 3, 8)

在您的代码中,您正在通过pandas库从Excel表中查询特定的单元格。该单元格恰好包含一个日期,pandas会检测到该日期并将其变成pandas.Timestamp对象。 pandas库不是Python标准库的一部分,因此,Python的datetime类不了解pandas.Timestamp。当将pandas.Timestamp传递给datetime构造函数时,您会收到错误消息TypeError: an integer is required (got type Timestamp)。这意味着datetime预期为整数(指定年份),但是收到了pandas.Timestamp,它不明白。

但是,pandas确实了解datetime,并为您提供了一个辅助功能to_pydatetime,可以将pandas.Timestamp转换为datetime对象(reference)。在您的代码中,将f的分配替换为:

f=h.to_pydatetime().date()

to_pydatetime()给您一个datetime.datetime对象,然后.date()将其变成datetime.date对象,下一行d=b-f所需,因为您为b分配了[ C0]。 

或者,您也可以将datetime.date.today()的声明更改为b,然后将b=dt.datetime.now()的赋值更改为f。这将为您提供精确的时差,而不仅仅是天数。

© www.soinside.com 2019 - 2024. All rights reserved.