Babak Abadkheir
Babak Abadkheir

Reputation: 2358

Checking time for executing if statement

I'm practising Python and I want to write a program that checks current time and see if it matches 2:12 pm and says: its lunch time So first I figured out using import time module, but I don't know how?

My problem is I don't know how to use time module for that. Or I'm using right syntax or not?

My code:

import time

bake=time()
if bake == '2:12':
    print ('its time to eating lunch')
else :
   print ('its not the time for eating lunch')

Upvotes: 1

Views: 17450

Answers (3)

adam
adam

Reputation: 1

What if we want to do something like:-

if local_time == between 12:00 and 12:30 :
    print ('its time to eating lunch')
else:
     
if local_time == between 6:30 and 7:00 :
   print ('its time to eat dinner')
else:

I mean, it's not correct, but you get the idea

Upvotes: -1

jagpreet
jagpreet

Reputation: 65

import datetime as da

lunch = "02:12 PM"

now = da.datetime.now().strftime("%I:%M %p")

if now == lunch:

  print("lunch time")

else:

  print("not lunch time")

Upvotes: -1

Nikolas Rieble
Nikolas Rieble

Reputation: 2621

I suggest the datetime module, which is more practicale in this case (as polku suggested). You will then directly access only hour and minute to check if it is lunch time.

Further information can be found here: How to get current time in python and break up into year, month, day, hour, minute?

import datetime
now = datetime.datetime.now()

if now.hour == 14 and now.minute == 12:
    print ('its time to eating lunch')
else :
    print ('its not the time for eating lunch')

Upvotes: 11

Related Questions