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"  
    
已邀请:
我在您发布的代码中可以看到一些问题。我希望将其中的一些内容指出,并提供一些有些重写的版本会有所帮助: 缩进被打破了,但我想这可能只是将其粘贴到Stack Overflow中的问题
strftime
用于格式化时间,而不是解析它们。你想要
strptime
而不是。 在Python中,
True
有一个大写
T
。 你正在定义
getDate
函数但从不使用它。 你永远不会退出你的
while
循环,因为你在成功输入后没有
break
。 在Python中对变量和方法名称使用“驼峰案例”被认为是不好的风格。 您在引用日期时使用“较旧”一词,但没有一年您不能说一个人是否比另一个人年长。 当您尝试解析日期时捕获任何异常,但不显示它或检查其类型。这是一个坏主意,因为如果你在该行上输错了变量名(或类似的错字),你就不会看到错误。 以下是修复这些问题的代码的重写版本 - 我希望从上面可以清楚地看到我做出这些更改的原因:
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"
    
有两个主要函数用于在日期对象和字符串之间进行转换:
strftime
strptime
。 strftime用于格式化。它返回一个字符串对象。 strptime用于解析。它返回一个datetime对象。 更多信息在文档中。 既然你想要的是一个日期时间对象,你会想要使用strptime。您可以按如下方式使用它:
>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)
请注意,没有解析年份会将默认值设置为1900。     
嗯,datetime.date.strftime需要datetime对象而不是string。 在您的情况下,最好的事情是手动创建日期:
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
    

要回复问题请先登录注册