Skip to main content
 首页 » 编程设计

python之使用 Python 3 的平均年龄计算器

2024年12月31日8jyk

我正在尝试使用 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(),错误应该会消失。