datetime在减去两个日期时不给出负秒和小时

datetime在减去两个日期时不给出负秒和小时

本文介绍了为什么python datetime在减去两个日期时不给出负秒和小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to known why I do not get minus hours and minus seconds from 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

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

all is as expected when the datetimes look like these;

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

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

returned is a datetime.timedelta of -1 days (datetime.timedelta(days=-1))

为什么当我将时间更改为;

why then when i change the times to;

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

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

我确实想知道是不是因为接近"午夜,但是

I did wonder if it was due to being 'near' midnight but

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

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

  • python 3.8.2
  • 熊猫 1.1.4

推荐答案

来自 timedelta 的文档:

From the documentation for timedelta:

内部仅存储天、秒和微秒.参数转换为这些单位:

  • 毫秒转换为 1000 微秒.
  • 一分钟转换为 60 秒.
  • 1 小时转换为 3600 秒.
  • 一周转换为 7 天.

然后将天、秒和微秒标准化,以便表示是唯一的,具有

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

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

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

So the number of seconds and microseconds are guaranteed to be non-negative, with the number of days being positive or negative as necessary. It makes sense to let the larger unit days be positive or negative, as that will account for most of an arbitrary interval. days can be slightly more negative than necessary, with the smaller, limited units used to make up the difference.

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

Note that with this representation, the sign of the interval is determined solely by the sign of the days.

这篇关于为什么python datetime在减去两个日期时不给出负秒和小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:47