如何检查 if 语句是否当前时间大于时间



我的代码遇到了困难,因为我试图传递 if 语句,当我的当前时间EPG_Now大于EPG_Now时间时。

示例:我当前的时间显示12:38AM不大于 12:55AM,因此除非我的当前时间在 12:55AM 之后,否则它不会传递 if 语句。

当我尝试这个时:

EPG_Time = time.strptime('07/10/2017 12:32AM', '%d/%m/%Y %H:%M%p')
self.EPG_Now = ['06/10/2017 11:55AM']
self.EPG_Next = ['07/10/2017 12:55AM']
for EPG_Now, EPG_Next in zip(self.EPG_Now, self.EPG_Next):
    EPG_Now_time = time.strptime(EPG_Now, '%d/%m/%Y %H:%M%p')
    EPG_Next_time = time.strptime(EPG_Next, '%d/%m/%Y %H:%M%p
    if EPG_Time > EPG_Next_time:
       print "it is time to delete the data from the list......................."

当我当前的时间不大于错误的EPG_Now时,它总是让我传递 if 语句。我想仅在当前时间大于 EPG_Now 时间时才传递 if 语句,然后我想做一些事情从列表中删除。

你能给我举个例子,如果我的当前时间大于EPG_Now时间,我如何才能传递 if 语句?

您的代码使一个简单的问题过于复杂。 试试这个:

>>> EPG_Time = time.strptime('07/10/2017 12:32AM', '%d/%m/%Y %H:%M%p')
>>> print EPG_Time
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=7, tm_hour=12, tm_min=32, tm_sec=0, tm_wday=5, tm_yday=280, tm_isdst=-1)
>>> EPG_Now = time.strptime('06/10/2017 11:55AM', '%d/%m/%Y %H:%M%p')
>>> print EPG_Now
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=6, tm_hour=11, tm_min=55, tm_sec=0, tm_wday=4, tm_yday=279, tm_isdst=-1)
>>> EPG_Next = time.strptime('07/10/2017 12:55AM', '%d/%m/%Y %H:%M%p')
>>> print EPG_Next
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=7, tm_hour=12, tm_min=55, tm_sec=0, tm_wday=5, tm_yday=280, tm_isdst=-1)
>>> EPG_Time > EPG_Next
False

这完全符合预期。我不认为你已经粘贴了你实际运行的代码——你在第 7 行缺少一个')。也许您的代码与原始问题不同步。

如果修复时间的字符串表示形式,以下内容可能会有所帮助:

from datetime import datetime
# Assume you have a list of datetime strings
#     Format: year-month-day-hour-minute-second
time_strs = ['2017-03-17-10-31-05', '2017-02-17-10-50-25']
# Extract each datetime unit and convert to ints
time_units = [[int(v) for v in dt.split("-")] for dt in time_strs]
# Create datetime objects from those units
time_objs = [datetime(*units) for units in time_units]
# You can now compare
if time_objs[1] > time_objs[0]:
    print(time_strs[1], " > ", time_strs[0])
else:
    print(time_strs[1], " < ", time_strs[0])

如果可以在不同的检查点存储时间并使用这些值,则应按照其他人的建议使用日期时间。举个例子:

import time
from datetime import datetime
past = datetime.now()
# Assume you slept for 10 seconds
time.sleep(10)
present = datetime.now()
if past < present:
    print("That's how time works!")

相关内容

最新更新