【发布时间】:2011-02-07 17:07:36
【问题描述】:
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()
如何检查我的当前时间是否介于两者之间?
my_event.start_time < current_time < my_event.end_time
【问题讨论】:
标签: python django datetime time
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()
如何检查我的当前时间是否介于两者之间?
my_event.start_time < current_time < my_event.end_time
【问题讨论】:
标签: python django datetime time
这是我检查两个不同时间段之间时间的脚本。一个早上一个晚上一个。这是使用@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
【讨论】:
接受测试的日期时间需要全部天真(无时区)或全部了解(时区)。如果您尝试比较有意识和幼稚,应该会发生异常。如果所有日期时间都知道,则时区实际上不必匹配,在比较时似乎考虑了这一点。
例如
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"
【讨论】:
我知道旧的,但由于这在 Google 搜索结果中非常高,所以这里的答案没有考虑两种情况:
我写了一个函数来处理时间比较,希望这对任何查看这个老问题的人有所帮助。
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
【讨论】:
如果比较三个日期,你可以使用简单的,像这样
if date1 < yourdate < date2:
...do something...
else:
...do ...
【讨论】:
只要 start_time 和 end_time 没有关联的 tzinfo 类,您的答案就是要走的路。您不能直接将天真的日期时间与时区日期时间进行比较。
【讨论】: