Reputation: 15824
In a Django website I maintain, I need to check whether users logged in (and performed a certain task) during particular time windows every day. These time windows are fixed and recur daily. For instance, window # 1 is between 3AM and 6:30AM (inclusive), whereas window # 2 is 11:50AM and 2:45PM (inclusive).
Whenever a user returns to the website, I retrieve time_now = datetime.datetime.now()
. And since I only care about the time, I use time_now.time()
. Next, I need to check whether time_now.time()
falls within any of the aforementioned time windows.
I'm unsure how to make that comparison in python. Particularly, how do I define the time objects governing the time windows? Will it be something like:
time_now = datetime.datetime.now()
now = time_now.time()
today3am = now.replace(hour=3, minute=0, second=0, microsecond=0)
today630am = now.replace(hour=6, minute=30, second=0, microsecond=0)
if today3am < now < today630am:
#do something
(and likewise for the second time window).
Please advise whether this is the correct way to do it or not. Alternatively, better methods (performance-wise) are also most welcome.
Upvotes: 0
Views: 2254
Reputation: 19821
I don't think you need to replace the hour
and minute
in current time. Because one you have obtained time()
from time_now
, you can just compare it with another time
object.
dt_now = datetime.datetime.now()
t_now = dt_now.time()
Now, you need the lower and upper bounds:
t_3am = datetime.time(hour=3, minute=0)
t_630am = datetime.time(hour=6, minute=30)
Once, you have these you can compare the time objects directly:
if t_3am < t_now <= t_630am: # used <= to make the upper bound inclusive
# do something
Performance wise, I would say you should treat t_3am
and t_630am
as constants because these are not going to change. So a better way would be to define it only once and not keep replacing the hour
and minute
everytime you get current time.
Upvotes: 2
Reputation: 3138
A few comments.
Yes, this is the correct way to compare datetime objects. The datetime docs show that datetime objects support arithmetic, multiplicative, and comparative operations.
I doubt the example code you provided above is going into production, but your if
statement is exclusive in that case, not inclusive like you mentioned in your question. I'm also sure you know how to change it to an inclusive if-statement, but I'll include it for others.
if today3am <= now <= today630am:
## This is true if now is
## 03:00 or 03:01
Performance wise, I'm not sure how granular you're looking to get. If logging the time is the only thing you care about, I would suggest using the time object in the datetime
module. This will create an object devoid of all date data, making the resulting object take up less RAM, presumably speeding up comparisons. However, I believe the difference between the two approaches will be negligible. I'll leave you to test this out and choose the approach that best supports your goals.
Upvotes: 1