将timedelta添加到datetime不移动到第二天

2024-04-18 14:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我用Python运行以下代码: from datetime import datetime, timedelta just_before_midnight = datetime(2014, 7, 16, 11, 59, 59) print just_before_midnight skip_midnight = timedelta(seconds=2) just_after_midnight_the_next_day = just_before_midnight + skip_midnight print just_after_midnight_the_next_day ... 它提供以下输出:

2014-07-16 11:59:59
2014-07-16 12:00:01

有人能解释为什么两种情况下的日期都是7月16日,而不是7月17日?你知道吗


Tags: the代码fromimportdatetimetimedeltanextjust
1条回答
网友
1楼 · 发布于 2024-04-18 14:55:18

因为那是上午11:59:59。你知道吗

您需要使用24小时的时间来查看预期的结果:

>>> just_before_midnight = datetime(2014, 7, 16, 23, 59, 59)
>>> just_after_midnight_the_next_day = just_before_midnight + timedelta(seconds=2)
>>> print just_before_midnight, just_after_midnight_the_next_day
2014-07-16 23:59:59 2014-07-17 00:00:01

相关问题 更多 >