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)
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
。这将为您提供精确的时差,而不仅仅是天数。