-1

Hello I want to check if the time A that I have in my dataset is night or day

import datetime
A
   datetime.datetime(2011, 4, 12, 12, 39, 58)
if  A < datetime.time(19):
    print 'day'
else:
    print 'night'

but I get the following error and I don't understand why

TypeError: descriptor 'time' requires a 'datetime.datetime' object but received a 'int'
emax
  • 6,965
  • 19
  • 74
  • 141
  • When you post code and an error message, make sure the code you post is the actual code that produced the error message. That `TypeError` indicates that you didn't actually import `datetime` the way your posted code does it. – user2357112 Nov 12 '15 at 20:02
  • you need *two* times (when it starts; when it ends). See [Python - Working out if time now is between two times](http://stackoverflow.com/q/20518122/4279) – jfs Nov 12 '15 at 20:52

2 Answers2

2
def get_cycle(dt):
    return "day" if 6 <= dt.hour < 19 else "night"

this would define day as anything between 6am and 7pm as daytime

if you wanted more flexibility

def get_cycle(dt):
    day_start = datetime.time(6,35) # day starts at 6:35am
    day_end = datetime.time(17,45) #day ends at 5:45pm
    return "day" if day_start <= dt.time() < day_end else "night"
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 1
    Use half-closed interval: `start <= dt.hour < end` i.e., include the start time so that it is equivalent to: `dt.hour in range(start, end)`. See [option a) described by Dijkstra](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html) – jfs Nov 12 '15 at 20:56
1
if A.hour < 19:
    print 'day'
else:
    print 'night'

But this will end up counting 19 out of 24 possible hours as daytime, which does not seem correct.

John Gordon
  • 29,573
  • 7
  • 33
  • 58