В вашем первом примере есть пара несовпадающих типов данных. Поскольку time.strftime
возвращает str
(строку), вы не можете сравнивать ее с int
(целые числа), которые присутствуют в my_list
. Более того, вы пытаетесь сравнить current_time
(это строка) с целым list
. Итак, первый пример можно исправить следующим образом:
import time
t = time.localtime()
current_time = time.strftime("%M", t) # here still a string
current_time = int(current_time) # converted to integer
my_list = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] # note these are all integers, so 05 is just 5
if current_time in my_list: # note operator "in"
print("its time to do something")
Мне лично больше нравится операция по модулю, так как она более лаконична. Однако вам нужно помнить, что 0
оценивается как False
, поэтому ваш оператор не сработает, когда вы захотите. Итак, вы можете отрицать оператор с помощью if not
, но для удобства чтения я бы просто явно поставил сравнение с желаемым значением 0
:
import time
t = time.localtime()
current_time = time.strftime("%M", t) # here still a string
current_time = int(current_time) # converted to integer
if current_time % 5 == 0: # note the explicit comparison with 0
print("its time to do something")
И, конечно, вместо того, чтобы делать полное преобразование time.strftime
и int
, вы можете просто использовать более компактный tm_min
:
import time
current_time = time.localtime()
if current_time.tm_min % 5 == 0: # note the explicit comparison with 0
print("its time to do something")