-2

Here is some prototyping code that given two dates will print the time between them:

from datetime import datetime
date_format= "%m/%d/%y"
now=datetime.now()
print now
d1=datetime.now()
d2=datetime.strptime('07/21/14',date_format)
delta= d2-d1
print delta

I'd like to modify this, such that it asks the user for two dates, instead of hardcoding the date in the source code.

So far, I've written:

date1=raw_input("What is date 1 ?:")
print date1
date2=raw_input("What is date 2 ?:")
print date2
delta=date2-date1
print delta

But after I type in my dates, I get the error:

Traceback (most recent call last):
  File "C:/Python27/datetimetest.py", line 17, in <module>
    delta=date2-date1
TypeError: unsupported operand type(s) for -: 'str' and 'str'
TooTone
  • 7,129
  • 5
  • 34
  • 60
  • possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – g.d.d.c Jul 18 '14 at 21:05
  • 2
    Are you asking how you could read in two dates from command line? – Andrew_CS Jul 18 '14 at 21:05
  • 3
    if it's solved, accept the given answer if that was the solution, or add an answer yourself and mark as accepted. Or failing that write a comment to say what the solution was. Please don't edit the title to say solved (I've undone that). – TooTone Jul 18 '14 at 22:17
  • possible duplicate of [Days between two dates in Python](http://stackoverflow.com/questions/8258432/days-between-two-dates-in-python) – Basil Bourque Nov 15 '14 at 12:22

1 Answers1

1

You need to convert the strings that you get from raw_input() into date objects. Like you do in the original code.

from datetime import datetime

date_format= "%m/%d/%y"

date1 = raw_input("What is date 1: ")
date1 = datetime.strptime(date1, date_format)

date2 = raw_input("What is date 2: ")
date2 = datetime.strptime(date2, date_format)

print
print 'Date 1:', date1
print 'Date 2:', date2
print 'Delta: ', date2 - date1

If we run this:

What is date 1: 3/14/12
What is date 2: 3/16/12

Date 1: 2012-03-14 00:00:00
Date 2: 2012-03-16 00:00:00
Delta:  2 days, 0:00:00
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173