In app engine I would like to call a function if the current time is between a particular 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()
Any better way of doing this.
-
This is more compact, but not so 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 properly, you may want to consider daylight saving time (use pytz for that -- it is possible to upload pytz bundled to your app to AppEngine) and seconds and millisecods as well (e.g. use
< '16:02'instead of<= '16:01', because the former doesn't depend on the second/subsecond precision. -
It seems like you might want datetime's "time" type, which doesn't care about 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's a more elegant way to handle the timezone adjustment using tzinfo, but I have to confess I've never dealt with timezones.
fholo : It's datetime.time. I'll edit the answer to make that clearer. I'm not sure why passing hour and minute as positional arguments wouldn't work, but you can keyword them: datetime.time(hour=9, minute=55)
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.