如果当前时间大于时间,如何检查if语句

时间:2017-10-06 23:42:12

标签: python python-2.7

我的代码很困难,因为我试图传递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语句的例子?

2 个答案:

答案 0 :(得分:1)

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

>>> 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行缺少')。也许您的代码与原始问题不一致。

答案 1 :(得分:0)

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

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!")