Skip to main content
 首页 » 编程设计

Python:比较日期并打印出第一个

2025年05月04日17artech

这可能非常简单,但我是 python 的初学者,我想通过提示用户输入 MM-DD 格式的日期来比较生日日期。没有年份,因为年份是当前年份 (2011)。然后它会提示用户输入另一个日期,然后程序会比较它以查看哪个是第一个。然后它打印出较早的一天和它的工作日名称。

示例:02-10 早于 03-11。 02-10是星期四,03-11是星期五

我刚开始学习模块,我知道我应该使用日期时间模块、日期类和 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"