我正在尝试使用 Python3 计算平均年龄(年 + 月格式)。我加载了一个 excel 文件并编写了以下代码:
import datetime
from datetime import date, timedelta
import pandas as pd
from pandas import ExcelFile
today = date.today()
agefile = pd.read_excel("test.xlsx", sheet_name = "birthdate")
age = pd.to_datetime(agefile["birthdate"], format = "%d/%m/%Y")
average_age = sum(((today - x) for x in age), timedelta(0)) / len(age)
最后一行没有用。它给了我这样的错误信息:
descriptor '__sub__' requires a 'datetime.datetime' object but received a 'datetime.date'
我花了很多时间弄清楚问题是什么,但到目前为止我还没有找到相关的答案。你能帮我解决这个问题吗?
最佳答案
date.today()
是一个date
,而age
中的x
都是日期时间
s。将 date.today()
更改为 datetime.today()
,错误应该会消失。
关于python - 使用 Python 3 的平均年龄计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123263/