I'm writing a python program that needs to do nothing between 23:00 and 8:00 depending on the time zone of the proxy it uses.
proxy_zone = get_timezone()
proxy_timezone = pytz.timezone(proxy_zone)
proxy_time = datetime.now(proxy_timezone)
now_time = proxy_time.time()
if now_time >= datetime_time(23, 00) or now_time <= datetime_time(8, 00):
future = datetime(proxy_time.year, proxy_time.month, proxy_time.day, 8, 0)
if proxy_time.hour >= 8:
future += timedelta(days=1)
bed_time = (future.astimezone(proxy_timezone) - proxy_time)
sleep(bed_time.total_seconds())
proxy_time is 6:45 so the timedelta (future.astimezone(proxy_timezone) - proxy_time
) returns should be 1 hour and 45 minutes.
But instead I get a timedelta of -1 day and 4 and a half hours.
As MrFuppes answered localizing the future converting the time to the correct timezone instead of localizing it was causing the issue.
proxy_time = datetime.now(proxy_timezone)
now_time = proxy_time.time()
if now_time >= datetime_time(23, 00) or now_time <= datetime_time(8, 00): # Sleep until 8:00
future = datetime(proxy_time.year, proxy_time.month, proxy_time.day, 8, 0)
if proxy_time.hour >= 8:
future += timedelta(days=1)
future = proxy_timezone.localize(future)
bed_time = (future - proxy_time).total_seconds()
event.nap(f'Sleeping for {bed_time} seconds')
sleep(bed_time) # sleep until morning