[Tutor] finding difference in time

Martin Walsh mwalsh at mwalsh.org
Fri May 15 22:21:18 CEST 2009


Kent Johnson wrote:
> On Fri, May 15, 2009 at 12:46 AM, R K <wolf85boy2008 at yahoo.com> wrote:
>> Gurus,
>>
>> I'm trying to write a fairly simple script that finds the number of hours /
>> minutes / seconds between now and the next Friday at 1:30AM.
>>
>> I have a few little chunks of code but I can't seem to get everything to
>> piece together nicely.
>>
>> import datetime,time
>> now = datetime.datetime.now()
>>
>> i = 0
>> dayOfWeek = datetime.datetime.now().strftime( '%a' )
>> while dayOfWeek != 'Fri':
>>     delta = datetime.timedelta( days = i )
>>     tom = ( now + delta ).strftime( '%a' )
>>     if tom != 'Fri':
>>         i = i + 1
>>     else:
>>         print i
>>         print tom
>>         break
>>
>> So with this code I can determine the number of days until the next Friday
>> (if it's not Friday already).
> 
> This could be simpler. I would write
> nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
>  while nextFriday.weekday() != 4:
>   nextFriday += datetime.timedelta(days=1)
> 
> Note the use of datetime attributes instead of relying on strftime().
> 
> What do you want the answer to be if you run the script at 1am Friday?
> at 2am Friday? If you want the next Friday in both cases, you could
> write this as
> nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
> nextFriday += datetime.timedelta(days=1) # Make sure to get a Friday
> in the future
>  while nextFriday.weekday() != 4:
>   nextFriday += datetime.timedelta(days=1)

I don't believe you'll get much better than that, IMHO.

But, dateutil (3rd party) probably deserves a mention, at least, for
this kind of job. I'm pretty sure the dateutil equivalent of Kent's
second approach would look something like this, but I haven't thoroughly
tested it, YMMV ...

from datetime import datetime
from dateutil.relativedelta import relativedelta, FR

now = datetime.now()
delta = relativedelta(
    days=1, weekday=FR, hour=1,
    minute=30, second=0, microsecond=0
)
nextFriday = now + delta

print nextFriday

...

dateutil totally rocks, and I hope someday soon it will be included in
the standard library.

http://labix.org/python-dateutil

HTH,
Marty







More information about the Tutor mailing list