Call function between time slots

In an application, I would like to call a function if the current time is between a certain interval. This is what I am doing now.

ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
    check_for_updates()

      

The best way to do it.

0


a source to share


2 answers


It sounds like you might want the "datetime" time type, which doesn't care about the date.

import datetime
ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)
# Turn this into a time object (no day information).
ist_time = ist_time.time()
if datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):
   ...

      



I'm sure there is a more elegant way of handling timezone setting using tzinfo, but I must admit that I have never dealt with timezones.

0


a source


It's more compact, but not as obvious:

if '09:55' <= time.strftime(
   '%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':
  check_for_updates()

      



Depending on how important it is for you to do the calculations absolutely correctly, you might think about daylight saving time (use pytz for that - you can add pytz to your application in the AppEngine) and seconds and milliseconds (for example, use < '16:02'

instead <= '16:01'

, because the former does not depend on second / subsecond precision.

+1


a source







All Articles