time between now and the next 2:30 am?

Jim jim.hefferon at gmail.com
Sat Jul 24 07:21:40 EDT 2010


On Jul 23, 8:52 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> > dt_twothirty=dt_localtime.replace(hour=settings.UPDATE_TIME_HOURS,minute=se ttings.UPDATE_TIME_MINS,second=0,microsecond=0)
>
> You're changing the time of day, but not the date. You might want to add
> a day to the shutdown time if it's earlier than the current time.

I started out by finding the right date (I used a less-than test and
toordinal and fromordinal() ).  However, after some trials, I came to
believe that I don't need to find the right date.  The part of that
calculation I need, and later refer to, is the .seconds attribute.  I
perceive that the way TimeDelta objects are laid out, the seconds
attribute will be the same, regardless of whether I calculate it using
2:30 today or first finding which is the right date and using its
2:30.

That is, as I understood it, if it is now 2:29 then the .seconds
attribute will be 60.  If it is now 2:31 then the .seconds attribute
will be 24*60*60-60.  I believe this holds regardless of which day I
use.

>>> import time,datetime
>>> x=datetime.datetime(2010,7,23)
>>> dt_localtime=x.fromtimestamp(time.time())
>>> dt_localtime
datetime.datetime(2010, 7, 24, 7, 17, 46, 122642)
>>> dt_twothirty=dt_localtime.replace(hour=2,minute=30,second=0,microsecond=0)
>>> print dt_twothirty
2010-07-24 02:30:00
>>> dd_diff=dt_twothirty-dt_localtime
>>> print dd_diff
-1 day, 19:12:13.877358
>>> dt_tomorrow_twothirty=dt_localtime.replace(day=25,hour=2,minute=30,second=0,microsecond=0)
>>> print dt_tomorrow_twothirty
2010-07-25 02:30:00
>>> dd_tomorrow_diff=dt_tomorrow_twothirty-dt_localtime
>>> print dd_tomorrow_diff
19:12:13.877358

Tested it, of course.  Not that I haven't gotten things wrong in the
past, even though I tested them.  :-}

Jim



More information about the Python-list mailing list