这可能非常简单,但我是python的初学者,我想通过提示用户以MM-DD格式输入日期来比较生日日期。没有年份,因为年份是当前年份(2011)。然后,它将提示用户输入另一个日期,然后程序将其进行比较,看看哪一个是第一个。然后它打印出较早的一天和它的星期名称。
示例: 02-10早于03-11。02-10是周四,03-11是周五
我刚开始学习模块,我知道我应该使用datetime模块、date类和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"
发布于 2011-03-13 17:03:58
在您发布的代码中,我可以看到一些问题。我希望这将有助于指出其中的一些,并提供一个稍微重写的版本:
Stack Overflow
strftime
的缩进被打破了,但我猜这可能只是粘贴到strptime
有一个大写的T
.函数,但从未使用过它。
while
循环,因为你在获得被认为风格不好的输入大小写之后,不会在Python中使用“驼峰大小写”作为变量和方法的名称。< break
>H219<代码>H120你在引用日期时使用了单词“getDate
”,但是如果没有一年,你就不能判断一个人是否比另一个人大。这里是你的代码的重写版本,它修复了这些问题--我希望从上面的内容中可以清楚地知道我为什么要做出这些改变:
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"
发布于 2011-03-13 16:52:08
嗯,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
发布于 2011-03-13 16:56:15
有两个主要函数用于在date对象和字符串之间进行转换:strftime
和strptime
。
strftime用于格式化。它返回一个字符串对象。strptime用于解析。它返回一个datetime对象。
更多信息in the docs。
由于您需要的是datetime对象,因此您可能希望使用strptime。您可以按如下方式使用它:
>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)
请注意,如果不解析年份,则会将缺省值设置为1900。
https://stackoverflow.com/questions/5288329
复制相似问题