简体   繁体   中英

Check if current time is in weekends Python

I am trying to code something like the following code. I would like my code to do nothing between the Friday 11PM and before the monday 1AM which should be the variable bgn and end but I don't manage to code the day and hour in thoese two variables.

import datetime

Now = datetime.datetime.now()      

bgn = 'Should be Friday 11 PM'
end = 'Should be Monday 1 AM'

if Now>bgn and Now<end:
    pass
elif:
    ...    

You should look at datetime weekday() method which gives you the number of the day in the week.

Basically (if I understand well) you dont want to do something in theses three differents cases:

  1. If the day is a saturday or sunday (it means in day 5 and 6)
  2. If the day is friday (day 4) but the hour is above 23h
  3. If the day is monday (day 0) but the hour is before 1h

So you can do something like this:

import datetime

now = datetime.datetime.now()

if now.weekday() in [5, 6] or (now.weekday() == 4 and now.hour >= 23) or (now.weekday() == 0 and now.hour <= 1):
   pass
else:
   (do stuff)

I'm pretty sure you can do something shorter and smarter but it do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM