Python:比较日期并输出第一个日期
这可能很简单,但我还是个Python初学者。我想让用户输入一个生日日期,格式是MM-DD(月份-日期),不需要年份,因为年份是当前的2011年。接着,程序会再让用户输入另一个日期,然后比较这两个日期,看看哪个日期更早。最后,程序会输出更早的那一天以及它是星期几。
举个例子:02-10比03-11早。02-10是星期四,而03-11是星期五。
我刚开始学习模块,知道应该使用datetime模块、日期类和strftime来获取星期几的名称,但我不太清楚怎么把这些结合起来。
如果有人能帮我入门,那就太好了!我已经有了一些零零碎碎的代码:
import datetime
def getDate():
while true:
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
userInput = datetime.date.strftime(birthday1, "%m-%d")
except:
print "Please enter a date"
return userInput
birthday2 = raw_input("Please enter another date (MM-DD): ")
if birthday1 > birthday2:
print "birthday1 is older"
elif birthday1 < birthday2:
print "birthday2 is older"
else:
print "same age"
3 个回答
1
有两个主要的功能可以用来在日期对象和字符串之间转换:strftime
和 strptime
。
strftime
是用来格式化的,它会返回一个字符串对象。
strptime
是用来解析的,它会返回一个日期时间对象。
更多信息可以在 文档中查看。
因为你想要的是一个日期时间对象,所以你应该使用 strptime
。你可以这样使用它:
>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)
注意,如果没有解析年份,默认会设置为1900年。
1
其实,datetime.date.strftime这个函数需要的是一个日期时间对象,而不是字符串。
在你的情况下,最好的办法是手动创建一个日期:
import datetime
...
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
month, day = birthday1.split('-')
date1 = datetime.date(2011, int(month), int(day))
except ValueError as e:
# except clause
# the same with date2
然后当你有了两个日期,date1和date2,你可以直接这样做:
if d1 < d2:
# do things to d1, it's earlier
else:
# do things to d2, it'2 not later
4
我看到你发的代码里有几个问题。希望指出这些问题能对你有帮助,并提供一个稍微改写过的版本:
- 缩进有问题,不过我猜这可能是你粘贴到Stack Overflow时出现的情况。
strftime
是用来格式化时间的,不是用来解析时间的。你应该用strptime
。- 在Python中,
True
的“T”是大写的。 - 你定义了
getDate
这个函数,但从来没有用到它。 - 你的
while
循环永远不会结束,因为在成功获取输入后你没有用break
跳出循环。 - 在Python中,给变量和方法命名时使用“驼峰命名法”被认为是不好的风格。
- 你在提到日期时用了“older”这个词,但没有年份的话,你无法判断一个人是否比另一个人年长。
- 你在尝试解析日期时捕获了任何异常,但没有显示出来或检查它的类型。这是个坏主意,因为如果你在那行代码中拼错了变量名(或者类似的错误),你就看不到错误信息了。
下面是一个修正了这些问题的代码版本——希望你能明白我为什么做这些改动:
import datetime
def get_date(prompt):
while True:
user_input = raw_input(prompt)
try:
user_date = datetime.datetime.strptime(user_input, "%m-%d")
break
except Exception as e:
print "There was an error:", e
print "Please enter a date"
return user_date.date()
birthday = get_date("Please enter your birthday (MM-DD): ")
another_date = get_date("Please enter another date (MM-DD): ")
if birthday > another_date:
print "The birthday is after the other date"
elif birthday < another_date:
print "The birthday is before the other date"
else:
print "Both dates are the same"