【问题标题】:Dates subtraction: has the event occurred or not?日期减法:事件是否发生?
【发布时间】:2015-11-13 09:30:48
【问题描述】:

如果我有每天的日期时间 - 如何找出事件是否已经发生,通过用 datetime.now()

减法

让我们在 15:35 举行日常会议。今天约翰来得更早 - 12:45,但亚历克斯迟到了 2 小时。和 15 分钟。 (17:40 到达)。

meet_dt = datetime(year=2015, month=8, day=19, hour=15, minute=35)
john_dt = datetime(year=2015, month=8, day=19, hour=12, minute=45)
alex_dt = datetime(year=2015, month=8, day=19, hour=17, minute=40)

print(meat_dt - john_dt) # came before > 2:50:00
print(meat_dt - alex_dt) # came after  > -1 day, 21:55:00

如果我少带走大日子 - 那么一切都很好,但相反我收到 -1 天,21:55:00 为什么不 -2:15:00,多么糟糕的一天?

【问题讨论】:

    标签: datetime python-3.x timedelta


    【解决方案1】:

    因为时间增量是标准化的

    timedelta 中除 days 字段之外的所有部分始终为非负数,as described in the documentation

    顺便说一句,如果你想先看看发生了什么,不要做这个减法。直接对比<即可:

    if then < datetime.datetime.now():
        # then is in the past
    

    【讨论】:

    猜你喜欢
    • 2015-05-15
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多