Adestin
Adestin

Reputation: 153

Compare two times (without dates) using the Python time module

How could something this simple be this tricky?

I want to create two times.

Time1 is a date-unaware time of UTC 8:30pm (20:30). Time2 is any other time (hour, minute, second) on the planet.

Hard as I've searched, the documentation and the stackoverflow examples all use the datetime module and include creating a date with the time. I just need to compare two times and, if needed, adjust Time2 to UTC.

Upvotes: 0

Views: 2353

Answers (1)

Adestin
Adestin

Reputation: 153

It turned out that @AdrienMatissart's comment was the clue needed to figure this simple issue out. The trick was to create a datetime object for today's date at 20:30 UTC. Then to create another datetime object for the current time. By localizing the current system time to UTC, daylight savings is accounted for and the datetime objects can be compared.

import pytz, datetime
UTC_TZ = pytz.utc

# use combine() to create a specific datetime in today's future
end = datetime.datetime.combine(datetime.date.today(), datetime.time(20, 30, tzinfo=UTC_TZ) )

# get the current system datetime and localize to account for daylight savings
right_now = datetime.datetime.now(tz=UTC_TZ)

# then I compare
if end > right_now: 
    # some action

Upvotes: 1

Related Questions