在Python中使用循环,范围和切片添加日期 [英] add days to a date in Python using loops, ranges, and slicing
问题描述
函数,循环,范围,for / if语句,以及字符串切片。
到目前为止,我有:
date = raw_input (输入以YYYY-MM-DD格式签出的日期:)
dueDate = raw_input(Book is due:)
length = len(date)
counter = 0
for i in range(length):
if date [i] == - :
counter = counter + 1
如果1 <计数器2:
打印日期
如果计数器> 2:
打印日期,太多连字符
如果计数器<= 1:
打印日期,不够连字符
然后我有:
year = date [0:4]
month = date [4:6]
day = date [6:10]
如果年==日期[0:4]:
年=年
如果月份==日期[4:6]:
月=月
如果day == date [6:10]:
day = day
打印年+月+日
我试图将其分解为YYYY-MM-DD,然后计算到期日期7日期从用户输入的日期。
程序的第二部分没有与第一部分一起工作,我不知道如何组合它们(或者如果那应该在那里)我必须使用一个函数吗?
闰年不需要考虑,我不能使用像datetime和时间因为我没有学习他们,我想写所有的代码你唱不同的循环变体和if / elif语句。
如果有人可以帮助我指出正确的方向,我真的很感激!
谢谢,
D
掌握其他技术后,我会说您还应该了解异常和日期时间模块。这是对日期验证有好处。
import datetime
/ pre>
while True:
try:
date = datetime.datetime.strptime(raw_input(输入以YYYY-MM-DD格式检出的日期:),%Y-%m-%d)
除了ValueError:
print日期未以以下格式插入:YYYY-MM-DD
else:
break
〜
I'm a beginner in python and I've recently learned how to do the basics of:
functions, loops, ranges, for/if statements, and string slicing.
So far I have:
date = raw_input("Enter the date checked out in YYYY-MM-DD format: ") dueDate = raw_input("Book is due:") length = len(date) counter=0 for i in range(length): if date[i] == "-": counter = counter + 1 if 1 < counter < 2: print date if counter > 2: print date,"too many hyphens" if counter <= 1: print date,"not enough hyphens"
Then I had:
year = date[0:4] month = date[4:6] day = date[6:10] if year == date[0:4]: year=year if month == date[4:6]: month = month if day == date[6:10]: day=day print year+month+day
I'm trying to break it down into YYYY-MM-DD and then compute a due date 7 days from the date the user entered.
The second part of the program didn't work with the first, I don't know how to combine them, (or if that should be there at all) would I have to use a function?
Leap years do not need to be accounted for, and I can not use modules like datetime and time since I haven't learned them and I want to write all the code using different variations of loops and if/elif statements.
If someone can help point me to the right direction I would really appreciate it!
Thanks,
D
解决方案Having mastered the other techniques, I'd say you should also learn about exceptions and the datetime module. It's good for the date verification here.
import datetime while True: try: date = datetime.datetime.strptime(raw_input("Enter the date checked out in YYYY-MM-DD format: "), "%Y-%m-%d") except ValueError: print "The date was not inserted in the following format: YYYY-MM-DD" else: break ~
这篇关于在Python中使用循环,范围和切片添加日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!