输入出生日期计算年龄python
时间: 2024-01-27 16:12:05 浏览: 153
可以使用 Python 中的 datetime 模块来计算年龄。具体实现代码如下:
```python
from datetime import datetime
def calculate_age(birth_date):
today = datetime.today()
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
return age
# 示例
birth_date = datetime(1990, 1, 1)
age = calculate_age(birth_date)
print(age) # 输出 31
```
其中,`birth_date` 是一个 `datetime` 类型的对象,表示出生日期。函数 `calculate_age` 返回一个整数,表示当前年龄。
相关问题
Python中#定义函数,输入出生日期,根据出生日期计算年龄 #定义函数 输入身份证号,返回出生日期和年龄
在Python中,你可以创建一个函数来计算用户的年龄,通常会通过接收两个参数:当前日期(可以用`datetime`模块获取)和用户提供的出生日期字符串。这里是一个简单的例子:
```python
from datetime import datetime
def calculate_age(birth_date_str):
# 将输入的生日字符串转换为日期格式
birth_date = datetime.strptime(birth_date_str, '%Y-%m-%d')
# 获取当前日期
today = datetime.now()
# 计算年龄
age = today.year - birth_date.year
if today.month < birth_date.month or (today.month == birth_date.month and today.day < birth_date.day):
age -= 1
return birth_date, age
# 使用函数示例
birth_date_input = "1990-05-20" # 假设这是用户提供的出生日期
birth_date, age = calculate_age(birth_date_input)
print(f"出生日期:{birth_date.strftime('%Y-%m-%d')}, 年龄:{age}")
```
在这个例子中,`calculate_age`函数接受一个字符串作为输入,然后计算出该人的实际年龄。需要注意的是,这个函数假设用户提供的日期格式是'YYYY-MM-DD'。
python输入出生日期和当前日期计算年龄
可以使用Python的datetime模块来计算年龄。首先,需要从用户那里获取出生日期和当前日期。然后,可以使用datetime模块中的date类来计算两个日期之间的差异,以得出年龄。
以下是一个示例代码:
```python
import datetime
# 获取出生日期和当前日期
birth_date = input("请输入出生日期(格式为YYYY-MM-DD):")
current_date = datetime.date.today().strftime("%Y-%m-%d")
# 计算年龄
birth_date = datetime.datetime.strptime(birth_date, "%Y-%m-%d").date()
current_date = datetime.datetime.strptime(current_date, "%Y-%m-%d").date()
age = current_date.year - birth_date.year - ((current_date.month, current_date.day) < (birth_date.month, birth_date.day))
# 输出结果
print("您的年龄是:", age)
```
在这个示例中,我们首先使用input函数从用户那里获取出生日期。然后,我们使用datetime模块中的date类将其转换为日期对象。接下来,我们获取当前日期,并将其转换为日期对象。最后,我们使用当前日期减去出生日期,并计算年龄。最后,我们使用print函数输出结果。
注意,这个示例假设用户输入的日期格式为YYYY-MM-DD。如果用户输入的格式不正确,程序将会抛出异常。因此,我们可以在程序中添加一些错误处理代码,以确保程序的健壮性。
阅读全文
相关推荐













