# 在 Python 中对日期时间做减法

## 在 Python 中使用 `datetime` 模块减去日期时间

`datetime` 是 Python 中的一个模块，它将支持操作 `datetime` 对象的函数。

`datetime` 也有函数 `now()`，它将当前日期和时间初始化到对象中。

``````from datetime import datetime

then = datetime(1987, 12, 30, 17, 50, 14)  # yr, mo, day, hr, min, sec
now = datetime(2020, 12, 25, 23, 13, 0)

print(now - then)
``````

``````12055 days, 5:10:00
``````

``````from datetime import datetime

def getDifference(then, now=datetime.now(), interval="secs"):

duration = now - then
duration_in_s = duration.total_seconds()

# Date and Time constants
yr_ct = 365 * 24 * 60 * 60  # 31536000
day_ct = 24 * 60 * 60  # 86400
hour_ct = 60 * 60  # 3600
minute_ct = 60

def yrs():
return divmod(duration_in_s, yr_ct)[0]

def days():
return divmod(duration_in_s, day_ct)[0]

def hrs():
return divmod(duration_in_s, hour_ct)[0]

def mins():
return divmod(duration_in_s, minute_ct)[0]

def secs():
return duration_in_s

return {
"yrs": int(yrs()),
"days": int(days()),
"hrs": int(hrs()),
"mins": int(mins()),
"secs": int(secs()),
}[interval]

then = datetime(1987, 12, 30, 17, 50, 14)  # yr, mo, day, hr, min, sec
now = datetime(2020, 12, 25, 23, 13, 0)

print("The difference in seconds:", getDifference(then, now, "secs"))
print("The difference in minutes:", getDifference(then, now, "mins"))
print("The difference in hours:", getDifference(then, now, "hrs"))
print("The difference in days:", getDifference(then, now, "days"))
print("The difference in years:", getDifference(then, now, "yrs"))
``````

`divmod()` 函数接受两个数作为被除数和除数，并返回它们之间的商和余数的元组。只有商是需要的，这也是为什么在代码中只使用 `0` 指数的原因。

``````The difference in seconds: 1041052966
The difference in minutes: 17350882
The difference in hours: 289181
The difference in days: 12049
The difference in years: 33
``````

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.