my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()
如何检查我当前的时间是否在他们之间?
my_event.start_time < current_time < my_event.end_time
答案 0 :(得分:7)
只要start_time和end_time没有关联的tzinfo类,您的答案就是可行的方法。您无法直接将天真日期时间与timezoned-datetime进行比较。
答案 1 :(得分:3)
你可以使用简单的比较三个日期,比如这个
if date1 < yourdate < date2:
...do something...
else:
...do ...
答案 2 :(得分:1)
我知道旧的,但由于谷歌的结果如此之高,这里的答案并未考虑两种情况:
我写了一个函数来处理时间比较,希望这可以帮助任何人查看这个老问题。
def process_time(intime, start, end):
if start <= intime <= end:
return True
elif start > end:
end_day = time(hour=23, minute=59, second=59, microsecond=999999)
if start <= intime <= end_day:
return True
elif intime <= end:
return True
return False
答案 3 :(得分:0)
获得测试的日期时间需要所有天真(无时区)或全部知晓(时区)。如果您尝试比较意识和天真,则应该发生异常。如果所有日期时间都知道时间区域实际上不必匹配,那么在比较时似乎会考虑到这些时区。
e.g。
class RND(datetime.tzinfo):
""" Random timezone UTC -3 """
def utcoffset(self, dt):
return datetime.timedelta(hours=-3)
def tzname(self, dt):
return "RND"
def dst(self, dt):
return datetime.timedelta(hours=0)
april_fools = datetime.datetime(year=2017, month=4, day=1, hour=12, tzinfo=pytz.UTC)
random_dt = datetime.datetime(year=2017, month=4, day=1, hour=9, tzinfo=RND())
random_dt == april_fools
# True as the same time when converted back to utc.
# Between test of 3 naive datetimes
start_spring = datetime.datetime(year=2018, month=3, day=20)
end_spring = datetime.datetime(year=2018, month=6, day=21)
april_fools = datetime.datetime(year=2018, month=4, day=1)
if start_spring < april_fools < end_spring:
print "April fools is in spring"
答案 4 :(得分:0)
这是我检查两个不同时间段之间时间的脚本。一种用于早上,一种用于晚上。这是使用@Clifford 脚本的扩展脚本
def Strategy_Entry_Time_Check():
current_time = datetime.datetime.now()
#current_time = current_time.replace(hour=13, minute=29, second=00, microsecond=00) #For testing, edit the time
morning_start = current_time.replace(hour=9, minute=30, second=00, microsecond=00)
morning_end = current_time.replace(hour=11, minute=00, second=00, microsecond=00)
evening_start = current_time.replace(hour=13, minute=00, second=00, microsecond=00)
evening_end = current_time.replace(hour=15, minute=00, second=00, microsecond=00)
if morning_start <= current_time <= morning_end:
print("Morning Entry")
return True
elif evening_start <= current_time <= evening_end:
print("Evening Entry")
return True
print("No Entry")
return False