Reputation: 141
I have this function for checking a specific time and day in the week. It should print 1 from Sunday 7:00PM to Friday 8:00PM And print 0 from Friday 8:00PM to Sunday 7:00PM
I checked the function on Friday around 11:00AM and 2:00PM and I'm getting the error message in the title.
Can someone explain exactly what the error means? And how I could maybe fix it? It's supposed to check the time in Eastern Standard Time always
import pytz
from datetime import datetime, time, date
est = pytz.timezone('EST')
Mon = 0
Tue = 1
Wed = 2
Thur = 3
Fri = 4
Sat = 5
Sun = 6
weekdays = [Mon, Tue, Wed, Thur]
edgecases = [Sun, Fri]
weekend = [Sat]
curr_day = datetime.now(tz=est).date().weekday()
curr_time = datetime.now(tz=est).time()
def checktime(curr_day, curr_time):
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
print(1)
elif curr_day in weekend or (curr_day == Fri and curr_time >= time(20,00,tzinfo=est)) or (curr_day == Sun and curr_time <= time(19,00,tzinfo=est)):
print(0)
Traceback error:
Traceback (most recent call last):
File ".\testingtime.py", line 73, in <module>
checktime(curr_day, curr_time)
File ".\testingtime.py", line 67, in checktime
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
TypeError: can't compare offset-naive and offset-aware times
Upvotes: 0
Views: 5438
Reputation: 1
This sorted it for me:
dt_obj = dt_obj.replace(tzinfo=None)
See python – Can’t subtract offset-naive and offset-aware datetimes ... answer 1
Upvotes: 0
Reputation: 25614
For one, if you call the time()
method on a tz aware datetime object, the resulting time
object will not carry the timezone info anymore - since it is assumed that it makes no sense without the date. Second, since you compare to static times, you don't need a timezone there. You can thus simplify your function to
def checktime(curr_day, curr_time):
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00)) or (curr_day == Fri and curr_time < time(20,00)):
print(1)
elif curr_day in weekend or (curr_day == Fri and curr_time >= time(20,00)) or (curr_day == Sun and curr_time <= time(19,00)):
print(0)
Upvotes: 1