timedelta Shifts Dates Across Month Ends

Shift dates with timedelta instead of hand-rolled month tables: cross-month adds, multiplied buffers, and negative steps keep calendar semantics.

PythonData Integrity

Code

pythonsnippet
19 lines
from datetime import date, timedelta

# 截止日 = 锚点日期 + 30 天:日期算术交给 datetime,别手写月长表
ship = date(2026, 1, 20)
deadline = ship + timedelta(days=30)
print('ship    :', ship)
print('deadline:', deadline)  # 一加就跨过 1 月

# 两个日期相减得到 timedelta:天数可直接比较与累加
left = deadline - date(2026, 1, 31)
print('gap days:', left.days)

# timedelta 支持倍数:两周缓冲就是 2 天 × 7
buffer = timedelta(days=2) * 7
print('buffer  :', buffer.days, 'days')
print('moved   :', ship + buffer)

# 负方向自然回退:月末长度差异由 datetime 处理
print('back    :', deadline - timedelta(days=35))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ship    : 2026-01-20
deadline: 2026-02-19
gap days: 19
buffer  : 14 days
moved   : 2026-02-03
back    : 2026-01-15

Reading the runtime

Module-level bindings hold the data — ship, deadline, left, buffer — with no function scope in between.

Putting it to use

Running the file prints labeled results such as deadline:, gap days: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `datetime`. Its state lives in module-level bindings: `ship`, `deadline`, `left`.