add days to a date in Python using loops, ranges, and slicing

余生颓废 提交于 2019-12-11 20:42:40

问题


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


回答1:


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
~                    



回答2:


First, your code is very hard to read in the site -- cleaning it up might help.

Second, look at the datetime module. It provides services for translating text into date objects, and then back out to text.

Once you've got a date object you can do a ton of stuff, like:

Python 2.7 (r27:82508, Jul  3 2010, 21:12:11) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timedelta
>>> d = datetime.strptime('2011-03-05','%Y-%m-%d')
>>> d
datetime.datetime(2011, 3, 5, 0, 0)
>>> d.strftime('%Y-%m-%d')
'2011-03-05'
>>> tomorrow = d+timedelta(days=1)
>>> tomorrow
datetime.datetime(2011, 3, 6, 0, 0)
>>> tomorrow.strftime('%Y-%m-%d')
'2011-03-06'

See: http://docs.python.org/library/datetime.html




回答3:


I would give datetime a try, even if you haven't learned it yet. I don't think it is complicated or difficult to learn. Using it will be far easier than any home-brewed method. Use datetime.date() for dates, and datetime.timedelta to add (or subtract) some number of days.

import datetime

datestr = raw_input("Enter the date checked out in YYYY-MM-DD format: ")
year,month,day = datestr.split('-')
date = datetime.date(year,month,day)
duedate = date + datetime.timedelta(days=7)
print 'Due date is : {0}'.format(duedate)



回答4:


Use can use timedelta function in datetime module

    from datetime import timedelta
    New_date=DateTime_obj-timedelta(days=No. of days to add)


来源:https://stackoverflow.com/questions/5206759/add-days-to-a-date-in-python-using-loops-ranges-and-slicing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!