繁体   English   中英

如何使用Python查找两个日期之间的年份差异? (如果一个人超过18岁,请进行锻炼)

[英]How can I find the difference in years between two dates using Python? (Work out if a person is over 18)

我的问题是,是否有人可以帮助我调试这段代码:

import datetime
print ("What is your date of birth? ")
dateofbirth = input("Please type your date of birth in a YYYY-MM-DD format ")
year, month, day = map(int, dateofbirth.split('-'))
dateofbirth1 = datetime.date(year, month, day)
today = datetime.date.today()
open('dateutil.tar').read()
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(today, dateofbirth1).years
if difference_in_years < 18
print ("Sorry, you are not eligible to vote.")
else
print ("You are over 18 and thus eligible to vote.")

我的目标是尝试编写一段代码,该代码可以在18岁以上且有资格投票的情况下解决。 这是通过要求该人输入出生日期,然后计算出他们的出生日期和今天的日期之间的年数差,然后使用IF语句告诉他们是否有投票权(例如,是否有投票权)来实现的。年的差异大于或小于18)。

目前,我在调试此代码时遇到一些问题。 首先,在第10行上有一个语法错误,我不确定该如何纠正。 其次,如果删除最后4行并再次运行代码,则会出现以下错误:

Traceback (most recent call last):
  File "C:\removed\canyouvote.py", line 8, in <module>
    open('dateutil.tar').read()
  File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 5: character maps to <undefined>

但是,很可能还有其他错误我目前无法解决。 不幸的是,由于我对编程还很陌生,所以我的知识和经验也不是很好,因此任何帮助将不胜感激! 在尝试研究解决方案时,我尝试使用我不熟悉的编码,因此请在错误之处纠正我。

提前非常感谢您!

出现UnicodeDecodeError的原因是,您试图打开并读取一个tarball(即二进制文件),就像它是文本文件一样。

当您执行此操作时,Python会尝试将文件的任意字节解释为它们代表了默认字符集(cp1252)中的字符,但这会在您幸运的情况下为您提供一个例外,或者在成功的情况下为您提供完整的垃圾你不是。 尝试在文本编辑器中打开dateutil.tar ,以查看它作为文本的意义。

很难说如何解决此问题,因为尚不清楚为什么首先要打开和读取该文件。 正如jonrsharpe指出的那样,您对结果不做任何事情。 而且我无法想象您如何对待他们。

如果要使dateutil可导入,那么执行此操作的方法不是对脚本中的压缩包进行任何操作,而是在运行脚本之前从脚本外部安装该模块。 最简单的方法是pip install dateutil ,它将自动找到正确的dateutil版本,下载,解压缩并安装它,以供所有脚本使用。

话虽如此,这里实际上并不需要dateutil 如果仅减去两个datetime对象,则会得到一个timedelta对象。


同时, SyntaxError来自以下代码:

if difference_in_years < 18
print ("Sorry, you are not elegible to vote.")
else
print ("You are over 18 and thus elegible to vote.")

在Python中,复合语句(如ifelse在套件之前需要冒号,并且套件必须缩进。 请参阅本教程的“ 编程第一步”部分。 所以:

if difference_in_years < 18:
    print("Sorry, you are not eligible to vote.")
else:
    print("You are over 18 and thus eligible to vote.")

(还要注意,我已经删除了括号前的空格,以适应PEP 8样式,并正确拼写为“ eligible”。)

如果没有dateutils模块,则可以计算出某人可以出生的最新日期为18岁。 因此,您甚至不需要解压缩tarball或真的担心额外的代码。 这是一个简单的示例,用于计算一个人的生日必须是18岁。

import datetime

now = datetime.datetime.today()   # Get a datetime object for today

days = (365 * 18) + (18 / 4)  # calculate days to go back along with leap years
back18 = now - datetime.timedelta(days=days)   # create another datetime object that represents the date the user needs to be to be 18.

然后,当您根据它们的输入创建日期时间对象时,就可以对其进行比较。

if birthdate >= back18:
    do stuff

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM