将timedelta更改为整数

时间:2016-12-13 14:15:01

标签: python datetime time int

好的,所以我必须建立一个计划,如果某人年龄超过18岁,那么他们是否可以投票。

然而,我正在努力解决如何让计划计算出生日期是否超过18年。我尝试了各种各样的事情,包括从今天开始的日期。

我认为能够更改出现日期为datetime.timedelta形式的出生日期与整数之间的差异更容易,然后可以在if语句中将其与18进行比较。

我不想要任何太复杂的事情。

这是我目前的代码:

from datetime import datetime
while True:
    inp = input("Enter date in format yyyy/mm/dd")
    try:
        then = datetime.strptime(inp, "%Y/%m/%d")
        break
    except ValueError:
        print("Invalid input")
diff = then - datetime.now()
diff = -diff
years = diff/365.25
years = int(years)
if years >= 18:
    print("You can vote")
else:
    print("You can't vote")

目前的问题是years = int(years),这是一种尝试改变它的蹩脚方式。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

# Python 2.7.10 
from datetime import datetime
while True:
    inp = raw_input("Enter date in format yyyy/mm/dd") # 1987/03/29
    try:
        then = datetime.strptime(inp, "%Y/%m/%d")
        break
    except ValueError as e:
        print e
        print("Invalid input")
diff = then - datetime.now()
diff = -diff

print dir(diff)
print diff.days

years = float(diff.days)/365.25 
if int(years) >= 18:
    print("You can vote")
else:
    print("You can't vote")

# 29.711156742 
>>> You can vote

# Python 3.5.2 
from datetime import datetime
while True:
    inp = input("Enter date in format yyyy/mm/dd")
    try:
        then = datetime.strptime(inp, "%Y/%m/%d")
        break
    except ValueError as e:
        print (e)
        print("Invalid input")
diff = then - datetime.now()
diff = -diff
years = float(diff.days)/365.25 
years = int(years)
if years >= 18:
    print("You can vote")
else:
    print("You can't vote")

>>> You can vote

答案 1 :(得分:0)

我认为years = int(years)是问题,请跳过它。这不会造成任何伤害。

then = datetime.strptime(inp, "%Y/%m/%d")
diff = datetime.now() - then
if diff.years/365.25 >= 18:
    print('You can vote.')
else:
    print('You can\'t vote')

答案 2 :(得分:0)

来自relativedelta库的

dateutils将完全按照您的要求执行操作 - 通过指定.years我们只输出两个日期之间的年数。

from datetime import datetime
from dateutil.relativedelta import relativedelta


while True:
    inp = input("Enter date in format yyyy/mm/dd: ")
    try:
        then = datetime.strptime(inp, "%Y/%m/%d")
        break
    except ValueError:
        print("Invalid input")

difference_in_years = relativedelta(datetime.now(), then).years

if difference_in_years >= 18:
    print("You can vote")
else:
    print("You can't vote")