[Tutor] datetime module problem
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."
>> date = raw_input("Enter date as month/day/year, or enter
>> nothing for today: ")
>> if date == "":
>> date = datetime.now()
>> print "Today's date entered"
>> 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 : from datetime import datetime
>In : n=datetime.now()
>In : n
>Out: datetime.datetime(2008, 4, 17, 8, 2, 15, 278631)
>Notice n has a time component.
>In : y=datetime.strptime('4/18/2008', '%m/%d/%Y')
>In : y
>Out: datetime.datetime(2008, 4, 18, 0, 0)
>y represents midnight on the given date.
>In : y-n
>Out: 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