Python在午夜的时间比较。

3

我需要以 AM PM 格式保存时间,但是在输入午夜时间时遇到了困难。

例如,某段时间为晚上9点到第二天早上6点。我需要按日分割它,如下所示:

t1 = datetime.datetime.strptime('09:00PM', '%I:%M%p').time()

t2 = datetime.datetime.strptime('12:00AM', '%I:%M%p').time()

t3 = datetime.datetime.strptime('06:00AM', '%I:%M%p').time()

现在我想知道t2应该是

12:00 AM还是11.59 PM

如果我使用12:00AM,那么我无法比较9pm > 12am,但11.59看起来很奇怪,也许是正确的方式。


据我所知,一天从凌晨12点到晚上11点59分。 - Maresh
所以,如果是11.59的话,我觉得还可以,但不知道为什么59这个数字看起来有点奇怪。不过,如果这是大家都使用的方式,那对我来说也没问题。 - user3214546
要么这样,要么也可以使用日期(天)进行比较。 - Tim
2
12:00AM 实际上是任何一天的 00:00。这只是人们在一天的第一个小时记录时间的常见方式。也许你应该在内部使用24小时制的时间,然后根据需要将其转换为上午/下午格式进行输入和输出。 - martineau
2个回答

9
你应该始终使用00:00(或12:00 AM)来表示午夜。
使用23:59(或11:59 PM)存在一些问题:
  • 比较中需要考虑时间精度。例如,23:59:01是否在午夜之前?23:59:59.9999呢?

  • 持续时间计算将受到所选精度的影响。注意,从10:00 pm到午夜是2小时,而不是1小时59分钟。

为了避免这些问题,你应该始终将时间间隔视为半开放间隔。也就是说,这个区间有一个包含的开始和排除的结束。在间隔符号表示中:[start, end) 现在关于跨越午夜的问题:
  • When you are comparing times that are associated with a date, you can just compare directly:

    [2015-01-01T21:00,  2015-01-02T06:00) = 9 hours
     2015-01-01T21:00 < 2015-01-02T06:00 
    
  • When you do not have a date, you can determine duration, but you cannot determine order!

    [21:00, 06:00) = 9 hours
     21:00 < 06:00  OR  21:00 > 06:00
    

    The best you can do is determine whether a time is between the points covered by the range.

    Both 23:00 and 01:00 are in the range [21:00, 06:00)
    21:00 is also in that range, but 06:00 is NOT.
    

    Think about a clock. It's modeled as a circle, not as a straight line.

  • To calculate duration of a time-only interval that can cross midnight, use the following pseudocode:

    if (start <= end)
        duration = end - start
    else
        duration = end - start + 24_hours
    

    Or more simply:

    duration = (end - start + 24_hours) % 24_hours
    
  • To determine whether a time-only value falls within a time-only interval that can cross midnight, use this pseudocode:

    if (start <= end)
        is_between = start <= value AND end > value
    else
        is_between = start <= value OR  end > value
    
请注意,在上述伪代码中,我所指的是值的大小,与数字上的比较有关 - 而不是逻辑时间值,正如之前所说,没有参考日期就不能独立比较。
此外,我的Pluralsight课程《日期和时间基础》(在“使用范围”部分的最后)也涵盖了其中很多内容。

1
关于半开区间以及为什么午夜应该是零的原因:E.W. Dijkstra: 为什么编号应该从零开始。这里是一个在Python中实现的time_diff()函数,用于计算时间间隔的代码示例:链接。还有一个in_between()函数的实现示例。 - jfs

0

要不这样,设定 t1 = 09:00PMt2 = 11.59PMt3 = 12:00AMt4 = 06:00AM。这样每天就有确定的时间范围了。当然,加上日期也能清楚地显示时间差。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接