嗨,我是使用
datetime
进行 Python 编程的新手(老实说,总的来说)。
所以我正在做一个项目,我需要检查用户是否超过 18 岁。我使用 timedelta
来获取今天和生日之间的差异,我还想检查月份和日期
我有这个代码:
...
import datetime
today = datetime.date.today()
...
birthday= request.form.get('birthday')
birth= datetime.datetime.strptime(birthday,'%Y-%m-%d').date()
year= datetime.timedelta(today.year - birth.year)
month= datetime.timedelta(today.month- birth.month)
day= datetime.timedelta(today.day- birth.day)
...
查看日期:
...
if year <= datetime.timedelta(18) and month <= datetime.timedelta(0) and day < datetime.timedelta(0):
flash('must have 18 years old to sign-up', category='error')
...
这是正确的吗?有没有更清晰的方法可以用更少的代码获得一切?预先感谢;)
这取决于你必须有多准确。 datetime 模块完全能够进行日期运算。
import datetime
today = datetime.date.today()
birthday = request.form.get('birthday')
birth= datetime.datetime.strptime(birthday,'%Y-%m-%d')
age = (today-birth).days / 365.25
print(age)
根据闰年的位置,这可能是休息日。