rocketchef
rocketchef

Reputation: 11

Comparing times of day in python

got my head in a bit of a twist with python time.

Quick summary: my app should read some times from a config (format example: '23:03') and then a while loop compares the current time to the config times, and performs certain actions if the minute of the day matches.

My issue is that when I'm writing the if statements, the time formats are slightly different, and it's not returning true when the times match.

while True:
    currentTime = datetime.datetime.now()
    morningTime = datetime.datetime(*time.strptime(config.get('general','morningTime'), "%H:%M")[:6])

    if (currentTime.time() == morningTime.time()):
        #do stuff! times match

    pprint (currentTime.time())
    pprint (morningTime.time())

This returns:

datetime.time(23, 3, 6, 42978)
datetime.time(23, 3)

I don't want an particularly want an exact match on anything smaller than a minute, so how should I compare the times?

Upvotes: 1

Views: 74

Answers (2)

Nuno André
Nuno André

Reputation: 5387

I highly recommend Arrow for data manipulation. You can do something like:

import arrow

current_time = arrow.now()
morning_time = arrow.get(config.get('general','morningTime'), 'HH:mm')

if current_time.minute == morning_time.minute:
    certain_actions()

'HH:mm' may vary depending on the format of morningTime.

Upvotes: 1

Felk
Felk

Reputation: 8234

You can discard the seconds and microseconds retrieved from a time object like this:

now = currentTime.time().replace(second=0, microsecond=0)
pprint(now) # should print something like datetime.time(23, 3)

And then just compare the times with == to get a match for times accurate to the minute only.

Upvotes: 3

Related Questions