Skip to content Skip to sidebar Skip to footer

Add Days To A Date In Python Using Loops, Ranges, And Slicing

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

Solution 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
~                    

Solution 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


Solution 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)

Solution 4:

Use can use timedelta function in datetime module

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

Post a Comment for "Add Days To A Date In Python Using Loops, Ranges, And Slicing"