Dick Moores wrote: > from datetime import datetime > > print "Enter 2 dates, first the earlier date, then the later date." > def getDate(): > date = raw_input("Enter date as month/day/year, or enter nothing for > today: ") > if date == "": > date = datetime.now() > print "Today's date entered" > else: > date = datetime.strptime(date, '%m/%d/%Y') > return date > > print "What's the earlier date?" > date1 = getDate() > print > print "What's the later date?" > date2 = getDate() > print > print "The difference between the dates is", (date2 - date1).days, 'days' > > However, when the earlier date (date1) is today's date entered by just > pressing Enter, the result is always 1 day too small. And I don't see > how to correct this, other than by adding the 1 (and I'd have to give up > using a function, I think). I still don't really get datetime. Help?
It's a rounding error. In [3]: from datetime import datetime In [4]: n=datetime.now() In [5]: n Out[5]: datetime.datetime(2008, 4, 17, 8, 2, 15, 278631) Notice n has a time component. In [8]: y=datetime.strptime('4/18/2008', '%m/%d/%Y') In [14]: y Out[14]: datetime.datetime(2008, 4, 18, 0, 0) y represents midnight on the given date. In [9]: y-n Out[9]: datetime.timedelta(0, 57464, 721369) So y-n is a fractional day, not a whole day. You could either create n with hours=minutes=0, or round the difference up to the next whole number of days. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor