Gregory6106 Gregory6106 - 1 year ago 50
Python Question

Python 3.2 input date function


I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.

I'm trying to start with something simple like:

import datetime

def getdate():
date1 = input(
return date1



This obviously doesn't work.

I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:

I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.

import datetime
from datetime import timedelta

d =, 1, 1)
year, month, day = map(int, d.split('-'))
d =, month, day)
d = dplanted.strftime('%m/%d/%Y')
d =

This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: '' object has no attribute 'split'

Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.

Thanks in advance!

Answer Source

The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.

You could go about that in two different ways:

  • Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:

    year = int(input('Enter a year'))
    month = int(input('Enter a month'))
    day = int(input('Enter a day'))
    date1 =, month, day)
  • Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:

    date_entry = input('Enter a date in YYYY-MM-DD format')
    year, month, day = map(int, date_entry.split('-'))
    date1 =, month, day)

Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)