<p>好的,对于每一行,你可以从下面应用函数<code>parseLine(str)</code>。我所做的基本上是:</p>
<p>对于给定的行(例如:<code>21:41:45 T:5796 NOTICE: 10:00PM</code>)I</p>
<ol>
<li>获取第一个时间戳,我们知道它的格式是<code>HH:MM:SS</code></li>
<li>获取第二个时间戳,我们知道它的格式是<code>HH:MM(AM/PM)</code></li>
<li>将两者转换为时间对象(请参见<a href="https://docs.python.org/2/library/datetime.html#time-objects" rel="nofollow">here</a>)</li>
<li>比较</li>
</ol>
<p>当然,您可以根据行的格式调整格式(以防您决定更改它)。重要的是正确地转换时间戳,因为第一个时间戳使用24小时格式,而第二个时间戳使用12小时格式(我使用<code>%I</code>将第二个时间戳的小时部分转换为24小时格式,以便我们可以轻松地比较两者)。比较本身是由Python和支持它的time对象完成的。我还假设两个时间戳都使用空格作为中间子字符串的分隔符,但是如果第一个时间戳由制表符分隔,则可以将<code>split()</code>的分隔符选项从<code>' '</code>更改为<code>'\t'</code>。你知道吗</p>
<pre><code>from datetime import datetime
def parseLine(line):
# Use split() and rsplit() to get the stamps
# Extract the first timestamp - it is separated from the rest by the first space in your string
first_tstamp = line.split(' ', 1)[0]
# Extract the second timestamp - it is separated from the rest by the last space in your string
last_tstamp = line.rsplit(' ', 1)[1]
# Parse the string representations of both stamps to a time object
t_first = datetime.strptime(first_tstamp, "%H:%M:%S").time() # Format: HH:MM:SS
t_second = datetime.strptime(last_tstamp, "%I:%M%p").time() # Format: HH:MM(PM/AM)
print("FIRST",t_first)
print("SECOND",t_second)
if(t_first > t_second): return 1
elif(t_first < t_second): return -1
else: return 0
def test(line):
res = parseLine(line)
if(res > 0): print("FIRST later than LAST")
elif(res < 0): print("FIRST earlier than LAST")
else: print("FIRST same as LAST")
print(" Test 1 ")
# First is earlier than second
test("21:41:45 T:5796 NOTICE: 11:00PM")
print(" Test 2 ")
# First is later than second
test("12:05:30 T:5796 NOTICE: 10:00AM")
print(" Test 3 ")
# First is same as second
test("23:00:00 T:5796 NOTICE: 11:00PM")
</code></pre>
<p>实际上,有多种解决方案,这可能不是最好的一个,但它确实做到了。我在最后做的测试的输出是:</p>
<pre><code>FIRST earlier than LAST # Because 21 is less than 11PM (=23)
FIRST later than LAST # Because 12 is greater than 10AM (=10)
FIRST same as LAST # Because 23 is the same as 11PM (=23)
</code></pre>