I have some code that needs to return a datetime
of the next 9am or 9pm, UTC. I've figured out some code to do this, but it feels unnecessarily complex to me. Is there a way to simplify this?
from datetime import datetime, timezone, timedelta
class NineOClockTimes:
@staticmethod
def get_next_nineoclock_time(current_time: datetime) -> datetime:
if current_time.hour < 9:
return NineOClockTimes._get_nineoclock_time(current_time, hour=9)
elif current_time.hour >= 21:
return NineOClockTimes._get_nineoclock_time(current_time, hour=9, next_day=True)
return NineOClockTimes._get_nineoclock_time(current_time, hour=21)
@staticmethod
def _get_nineoclock_time(current_time, hour, next_day=False):
new_time = current_time.replace(
hour=hour,
minute=0,
second=0,
microsecond=0,
tzinfo=timezone.utc,
)
if next_day:
new_time += timedelta(days=1)
return new_time
current_time
was 9:49 AM in UTC+1 timezone? (8:49 AM UTC) \$\endgroup\$