【问题标题】:Python: comparing dates and print out the first onePython:比较日期并打印出第一个
【发布时间】:2011-03-13 08:37:10
【问题描述】:

这可能很简单,但我是 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"  

【问题讨论】:

  • 你有一些缩进问题,这很明显。为什么你只使用一次try?你读了两个日期。我真的不明白你的动作。您应该首先阅读一个好的 Python 语言教程。 docs.python.org/tutorial/index.html

标签: python datetime date strftime


【解决方案1】:

我可以在您发布的代码中看到一些问题。我希望指出其中的一些内容会有所帮助,并提供一个稍微改写的版本:

  • 缩进已损坏,但我想这可能只是将其粘贴到 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"

【讨论】:

  • 非常感谢!是的,从我所拥有的来看,它肯定比以前更清晰。我正在使用 python 介绍书,它并没有真正详细介绍模块/对象的功能以及何时/如何使用它们。我认为是时候换一个新的更好的了哈哈。
【解决方案2】:

有两个主要函数用于在日期对象和字符串之间进行转换:strftimestrptime

strftime 用于格式化。它返回一个字符串对象。 strptime 用于解析。它返回一个日期时间对象。

更多信息in the docs

由于你想要的是一个日期时间对象,你会想要使用 strptime。您可以按如下方式使用它:


>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)

请注意,不解析年份会将默认设置为 1900。

【讨论】:

    【解决方案3】:

    嗯,datetime.date.strftime 需要 datetime 对象而不是字符串。

    在您的情况下,最好的办法是手动创建日期:

    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
    

    【讨论】:

    • 是的,谢谢,会解决的。好的风格永远是好的风格,即使在例子中也是如此。再次感谢。
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多