Sac*_*ani 6 python python-3.x python-datetime pandas
我有以下格式的 Excel 表格:
我想使用pandas模块使用 Python 读取此表并计算发布日期和当前日期之间的差异。这是我当前的代码:
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()
Run Code Online (Sandbox Code Playgroud)
它在第 7 行 ( f=dt.datetime(h)) 中显示错误。它读TypeError: an integer is required (got type Timestamp)。
f9c*_*534 13
该datetime模块是 Python 标准库的一部分。datetime.datetime该类的构造函数将特定的年、月和日作为参数(参考)。你会调用它,例如datetime.datetime(2020, 3, 8)。
在您的代码中,您通过pandas库从 Excel 表中查询特定单元格。这个单元格恰好包含一个日期,它pandas检测并变成一个pandas.Timestamp对象。该pandas库不是 Python 标准库的一部分,因此 Python 的datetime类不知道pandas.Timestamp. 当您将 a 传递pandas.Timestamp给datetime构造函数时,您会收到错误消息TypeError: an integer is required (got type Timestamp)。这意味着datetime期望一个整数(指定年份),但收到一个pandas.Timestamp它不理解的 。
但是,pandas确实知道datetime并为您提供了一个帮助函数to_pydatetime来将 apandas.Timestamp变成一个datetime对象(reference)。在您的代码中,将分配替换为f:
f=h.to_pydatetime().date()
Run Code Online (Sandbox Code Playgroud)
该to_pydatetime()给你一个datetime.datetime对象,然后.date()把它变成一个datetime.date对象,这是必需的d=b-f下一行,因为你指定b用datetime.date.today()。
或者,你也可以改变的声明b来b=dt.datetime.now(),然后的任务f来f=h.to_pydatetime()。这将为您提供精确的时差,而不仅仅是天数的差异。
| 归档时间: |
|
| 查看次数: |
8052 次 |
| 最近记录: |