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.
Code
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-15Reading 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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.