[Tutor] datetime module problem

Dick Moores rdm at rcblue.com
Thu Apr 17 15:05:08 CEST 2008

At 05:10 AM 4/17/2008, Kent Johnson wrote:
>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 "What's the later date?"
>>date2 = getDate()
>>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.


Man, I don't think I've ever been so frustrated with Python as I am 
with it's datetime module. I had guessed correctly at WHY I was 
getting that error, but I have no idea how to implement either of 
your suggestions as to how to eliminate it. Could you please spell 
them both out?

Here's my script again: <http://py77.python.pastebin.com/f3f6882a4>



UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/ 

More information about the Tutor mailing list