Home > Back-end >  how to compare a variable to a time format?
how to compare a variable to a time format?

Time:12-21

I need the variable entered by the user to look like the time (for example 15:25), if it is not called else my code


if message.text == ???:
      bot.send_message(message.chat.id,f'Напомню вам о тренировке в {message.text}')
      schedule.every().day.at(message.text).do(bot.send_message,message.chat.id, 'Время тренировки!')
      while True:
         schedule.run_pending()
         time.sleep(1)
else:
      firts = bot.send_message(message.chat.id,f'Вы неправильно указали формат времени, попробуйте еще раз.')
      bot.register_next_step_handler(firts, gonap)


I only came up with the idea to directly write

if message.text == "%Y-%m"

,but this did not give any result

Thank you so much for your help.

CodePudding user response:

You can use strptime()

from datetime import datetime

my_date_1 = "15:25"
my_date_2 = "25:25"

try:
    datetime.strptime(my_date_1, "%H:%M")
    print(True)
except ValueError:
    print(False)
    
try:
    datetime.strptime(my_date_2, "%H:%M")
    print(True)
except ValueError:
    print(False)

Output:

True
False

So your code will be something like this:

try:
    datetime.strptime(message.text, "%H:%M")
    bot.send_message(message.chat.id,f'Напомню вам о тренировке в {message.text}')
    schedule.every().day.at(message.text).do(bot.send_message,message.chat.id, 'Время тренировки!')
    while True:
        schedule.run_pending()
        time.sleep(1)
except ValueError:
    firts = bot.send_message(message.chat.id,f'Вы неправильно указали формат времени, попробуйте еще раз.')
    bot.register_next_step_handler(firts, gonap)
  • Related