在 Python 中处理闰年
我有一个程序,用户输入一个日期,然后将其与另一个日期进行比较,看看哪个日期先出现。
我该如何编写一段代码,让用户输入 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"
I have a program where the user enters a date and then compares it to another date to see which one comes first.
How would I go about writing a code where the user inputs Feb 29 and the program returns Feb 28 instead (since there is no leap year)?
Example:
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何比较日期?如果您使用
datetime
函数,那么这应该已经考虑到了这种东西。datetime.timedelta()
用于表示两个日期之间的差异不知道这如何适合您的代码,但它可能是一个选项;-)
How do you compare dates? If you use the
datetime
functions then this should already account for this sort of stuff.datetime.timedelta()
is used to represent the difference between two datesDon't know how this fits in your code, but it may be an option ;-)
如果您要检查:
month == 2 and day == 29
,那么使用 calendar.isleap()。如果将date
/datetime
设置为非闰年的 2 月 29 日,则会引发ValueError
。If you are checking that:
month == 2 and day == 29
it is redundant to also check if it is a leap year with calendar.isleap(). Adate
/datetime
would raise aValueError
if it was set to Feb 29th on a non-leapyear.