【问题标题】:Comparing two times without date in Python?在 Python 中比较没有日期的两次?
【发布时间】:2021-10-26 04:35:27
【问题描述】:

假设我有两次没有日期,如下所示。

>>> time_1 = datetime.datetime.strptime("05:30", "%H:%M")
>>> time_2 = datetime.datetime.strptime("05:00", "%H:%M")

要比较这两者,我可以这样做:

>>> time_1<= time_2
False

现在,对于这个例子,当我知道 03:30 发生在“23:30”之前,我也会得到 False

>>> time_1=datetime.datetime.strptime("23:30", "%H:%M")
>>> time_2=datetime.datetime.strptime("03:30", "%H:%M")
>>> time_1<= time_2
False

我想知道有没有办法处理这种情况?

【问题讨论】:

  • ...但03:30 不会发生在23:30 之前。 Python 正在做正确的事情。如果您将时间与 第二天 的另一个时间进行比较,您可以添加 1 天,例如time_2 += datetime.timedelta(days=1).
  • @Selcuk 我同意。我正在处理一个循环时间,即 23:30 发生在第二天凌晨 3:30 之前。
  • 有截止日期吗?晚上 8 点也应该在凌晨 3 点之前到来吗?
  • @MrFuppes 不知道怎么做?
  • @Selcuk 截止时间为 24:00

标签: python datetime time


【解决方案1】:
if time2 < time1:
   time2 += datetime.timedelta(days=1)

如果第二次小于第一次,则假设第二次总是第二天

【讨论】:

  • 不确定这有什么帮助。这将导致time1 &lt;= time2 始终返回True,使其成为重言式。
  • 确实如此。 @Joran 建议的方式会导致该问题。
  • 此外,没有为 datetime.time 类定义 timedelta 算法
  • @MrFuppes 这是datetime,而不是time
  • @Selcuk 添加任意日期无助于解决我认为的问题
【解决方案2】:

假设时间字符串代表一个时间序列,即它们按时间顺序出现,可以通过将持续时间添加到任意日期(我必须修改我的评论@Selcuk ...)。类似的东西

from datetime import datetime, time, timedelta

# assuming the "cyclic time" looks similar to this:
cycletimes = ["05:00", "05:30", "23:30", "03:30"]

# we can convert to timedelta;
# to_td converts HH:MM string to timedelta
to_td = lambda s: timedelta(hours=int(s.split(':')[0]), minutes=int(s.split(':')[1]))
durations = list(map(to_td, cycletimes))

# take an arbitrary date
refdate = datetime.combine(datetime.today().date(), time.min)
# what we want is datetime; we can already set the first entry
datetimes = [refdate+durations[0]]

# now we iterate over cycle times; if the next value is smaller, we add a day to refdate
for t0, t1, d in zip(cycletimes[:-1], cycletimes[1:], durations[1:]):
    if t1 < t0:
        refdate += timedelta(1)
    datetimes.append(refdate+d)


print(f"{datetimes[0]} <= {datetimes[1]} -> {datetimes[0] <= datetimes[1]}")
# 2021-08-26 05:00:00 <= 2021-08-26 05:30:00 -> True

print(f"{datetimes[2]} <= {datetimes[3]} -> {datetimes[2] <= datetimes[3]}")
# 2021-08-26 23:30:00 <= 2021-08-27 03:30:00 -> True

现在例如“23:30”出现在之前“03:30”,而不是在你只比较时间之后。旁注,纯 Python 很好地说明了这里的逻辑;但在“现实世界”中,我建议您查看 pandas 库以完成此类任务。

【讨论】:

  • 谢谢- 对列表元素做了一个小改动,我使用建议的方法得到了这个:cycletimes = ["05:30", "05:00", "23:30", "21 :30"] 2021-08-26 05:30:00 真 2021-08-27 23:30:00 真
  • @armin 因为你没有注意我上面所说的约束:“按时间顺序出现”;-) 你的例子行不通-我不行查看任何合理的逻辑如何处理任意出现的时间,我认为您必须包含约束。
猜你喜欢
  • 1970-01-01
  • 2016-02-24
  • 2022-01-05
  • 1970-01-01
  • 2018-02-17
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多