Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to compare a variable to a time format?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you so much for your help.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading