1

i am working with raspberry pi (python), i wanted to start reading a file at specific time of the the day, but the problem every time i try to compare between real time and my required time i don't get any thing and sometimes i get. typeerror:c an't compare datetime.time to str

import datetime

import time

timee = (" %s" %time.strftime("%H:%M:%S"))


t = datetime.time(14, 30, 00)

t1 = datetime.time(15, 30, 00)

if (timee >= t and timee <= t1):
    print ('this is right')
Rakesh
  • 81,458
  • 17
  • 76
  • 113
qarn.ooz
  • 29
  • 1
  • 7
  • Using local time like this is ok, unless your area uses daylight saving time. If that's the case, you need to make sure that a daylight saving changeover doesn't occur in the time interval between `t` and `t1`. – PM 2Ring Jul 17 '18 at 07:57

3 Answers3

1

You can use just the datetime module.

Ex:

import datetime

t = datetime.time(14, 30, 00)
t1 = datetime.time(15, 30, 00)

if (t <= datetime.datetime.time(datetime.datetime.now()) <= t1):   #Check if current time is between t and t1
    print ('this is right')
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

The problem is the strftime method you are using. It returns a string of the time and not a datetime.time object. Look at this answer for getting the current time. Reproducing what is in the answer: datetime.datetime.now().time()

Priyank
  • 1,513
  • 1
  • 18
  • 36
0

One possible solution (another one is using datetime.now() function for getting current time):

import datetime
import time

# timee = ("%s" % time.strftime("%H:%M:%S"))
timee = time.strftime("%H:%M:%S") # no need to format it as string here

t = datetime.time(14, 30, 00)
t1 = datetime.time(15, 30, 00)

if t <= datetime.time(*[int(i) for i in timee.split(':')]) <= t1:
    print ('this is right')

Prints this is right if time is between 14:30:00 and 15:30:00 (included).

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91