为什么 python datetime 在减去两个日期时不给出负数的秒数和小时数?

Why doesn't python datetime give negative seconds and hours when subtracting two dates?

我想知道为什么我没有从 datetime.timedelta 得到负小时和负秒?

我有以下方法

def time_diff(external_datetime, internal_datetime):

    from pandas.core.indexes.period import parse_time_string # include for completeness 

    time_external = parse_time_string(external_datetime)[0]
    time_internal = parse_time_string(internal_datetime)[0]

    diff = time_external - time_internal
    return diff

当日期时间看起来像这样时,一切都符合预期;

external_datetime = "2020-01-01T00:00:00"
internal_datetime = "2020-01-02T00:00:00"

返回的是 datetime.timedelta -1 天 (datetime.timedelta(days=-1))

为什么我把时间改成;

external_datetime = "2020-01-01T00:00:00"
internal_datetime = "2020-01-01T01:30:00"

我得到 datetime.timedelta(days=-1, seconds=81000)

的差异吗

我确实想知道是不是因为 'near' 午夜但是

external_datetime = "2020-01-01T11:00:00"
internal_datetime = "2020-01-01T11:30:00"

结果 datetime.timedelta(days=-1, seconds=84600)

版本

计算中的时间通常基于经过参考时间的秒数(或某些秒单位)。我假设 Python 的 DateTime 将数据表示为一天开始后的小时、分钟、秒和秒的子单位。因此,seconds 永远不会为负。因为它总是在秒之后,所以 -1 天 + 84600 秒是有意义的,所以秒是正数。

来自documentation for timedelta

Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

  • A millisecond is converted to 1000 microseconds.
  • A minute is converted to 60 seconds.
  • An hour is converted to 3600 seconds.
  • A week is converted to 7 days.

and days, seconds and microseconds are then normalized so that the representation is unique, with

  • 0 <= microseconds < 1000000
  • 0 <= seconds < 3600*24 (the number of seconds in one day)
  • -999999999 <= days <= 999999999

因此秒数和微秒数保证为非负数,天数根据需要为正数或负数。让较大的单位 days 为正或负是有意义的,因为这将占任意间隔的大部分。 days 可能会比必要的负数稍微多一些,使用较小的有限单位来弥补差异。

请注意,在这种表示中,间隔的符号仅由天数的符号决定。