【问题标题】:Handling leap years in Python在 Python 中处理闰年
【发布时间】:2011-07-16 04:50:33
【问题描述】:

我有一个程序,用户输入一个日期,然后将其与另一个日期进行比较,看看哪个日期在前。

我将如何编写代码让用户输入 2 月 29 日,而程序返回 2 月 28 日(因为没有闰年)?

例子:

def date(prompt):
''' returns the date that user inputs and validates it'''  
while True:
    try:
        date = raw_input(prompt)
        if len(date) >= 5:
            month = date[0:2]
            day = date[3:5]
        dateObject = datetime.date(2011, int(month), int(day))
        return dateObject
    except ValueError:
            print "Please enter a valid month and day"

【问题讨论】:

  • 这对我来说听起来很像家庭作业。如果是,请添加作业标签,您更有可能得到对您有帮助的答案。
  • 在这种情况下,我不会返回不同的日期,而是告诉用户该日期不存在并重试。您可以为此使用递归。
  • @carpetsmoker 我可以这样做,但我想让程序自动输入日期,如果可能的话,可以是 3 月 1 日或 2 月 28 日 :)
  • 对,好吧,这很明显......使用我的回答中提到的calender.isleap()...... 如果calender.isleap(年)和月== 2和日== 29: day = 28 ...还是我错过了什么?

标签: python error-handling leap-year


【解决方案1】:

如果您正在检查:month == 2 and day == 29,那么用calendar.isleap() 检查它是否是闰年是多余的。如果将date/datetime 设置为非闰年的 2 月 29 日,ValueError 将引发ValueError

【讨论】:

    【解决方案2】:

    你如何比较日期?如果您使用 datetime 函数,那么这应该已经解决了这类问题。

    >>> datetime.datetime(2011, 2, 28)
    datetime.datetime(2011, 2, 28, 0, 0)
    
    >>> datetime.datetime(2011, 2, 29)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: day is out of range for month
    
    >>> datetime.datetime(1600, 2, 29)
    datetime.datetime(1600, 2, 29, 0, 0)
    

    datetime.timedelta()用于表示两个日期之间的差异

    >>> datetime.datetime(2011, 2, 28) + datetime.timedelta(days=10)
    datetime.datetime(2011, 3, 10, 0, 0)
    
    >>> datetime.datetime(1600, 2, 28) + datetime.timedelta(days=10)
    datetime.datetime(1600, 3, 9, 0, 0)
    
    >>> datetime.datetime(2011, 2, 28) - datetime.datetime(2011, 4, 10)
    datetime.timedelta(-41)
    

    不知道这如何适合您的代码,但它可能是一个选项 ;-)

    【讨论】:

    • 我认为你的代码不适合我的编码,不过还是谢谢!! :)
    • 在这种情况下,您可以使用calender.isleap() 检查给定年份是否为闰年...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2017-10-04
    相关资源
    最近更新 更多