At 02:37 PM 4/15/2008, Kent Johnson wrote:
>Dick Moores wrote:
>>I'm really struggling with the datetime module. Trying for a script
>>that will calculate the number of days between any two dates
>
>How about this:
>
>from datetime import datetime
>date1 = raw_input("Enter date1 as year-month-day: ")
>date1 = datetime.strptime(date1, '%Y-%m-%d')
>date2 = raw_input("Enter date2 as year-month-day: ")
>date2 = datetime.strptime(date2, '%Y-%m-%d')
>print "date2 - date1 is", (date2 - date1).days, 'days'
>
>Kent
Yes, thanks, Kent.
I finally tracked down that table for the format string, at
< http://docs.python.org/lib/module-time.html>. Been experimenting
with it. Realized that the format string could be the more familiar
American '%m/%d/%Y', or '%m/%d/%y'.
The docs are so hard for me to understand, that I'm even feeling
pleased with myself for this:
from datetime import datetime
date1 = raw_input("Enter date1 as year-month-day: ")
date1 = datetime.strptime(date1, '%m/%d/%Y')
today = datetime.now()
print "today - date1 is", (today - date1).days, 'days'
But then I thought it would be handy for the user to be able to just hit Enter for today's date for either the earlier date or the later one, and came up with:
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?
Thanks,
Dick Moores
UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor