将出生日期转换为数字年龄Python

时间:2018-04-10 18:16:03

标签: python

谢谢大家,我很亲近。我在名为Decipher的调查软件工具中使用Python,因此它可能看起来有点不同。我现在的问题是我需要" pipe"在基于受访者回答的年龄中,那将是your_date_string。但是当我把它放在我的dob变量中时,我从系统中得到一个错误:ValueError:time data' your_date_string'与格式&%;%Y,%d,%m'不匹配,但打印your_date_string会返回所需的确切值。不知道如何解决这个问题。

from datetime import date

your_date_string = str(2003 - (scr_q2c.c1.val)) +","+ str(scr_q2b.c1.val + 1) +","+ str(scr_q2a.c1.val + 1)
year, day, month = [int(f) for f in your_date_string.split(',')]
your_date = date(year, month, day)

dob = datetime.datetime.strptime('your_date_string', '%Y,%d,%m')
today = datetime.date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob .month, dob .day))

print your_date_string
print age

2 个答案:

答案 0 :(得分:1)

首先需要将字符串转换为日期对象:

from datetime import date

your_date_string = '1982,14,4'
year, day, month = [int(f) for f in your_date_string.split(',')]
your_date = date(year, month, day)

然后使用该日期对象计算年数。一种快速简便的方法是依靠dateutil第三方库,您可以使用pip install dateutil进行安装。这是一个例子:

from dateutil.relativedelta import relativedelta

difference_in_years = relativedelta(date.today(), your_date).years

在此示例中,difference_in_years = 35

答案 1 :(得分:0)

检查月份和日期,如果今天小于出生日期,则从年份差减去

import datetime
dob = datetime.datetime.strptime('1982,14,4', '%Y,%d,%m')
today = datetime.date.today()
print today.year - dob.year - ((today.month, today.day) < (dob .month, dob .day))