2022年 11月 13日

Python 关于日期相减 获得两个日期的天数差

我们在实际工作中,经常需要 对 两个日期进行 相减,从而获取两个日期的 时间差

如:2022-09-01

如:2022-09-09

输出:时间相差 8 天

import datetime
import time

a = '2022-9-1' # 想被减的时间
a_s = tuple(time.strptime(a,"%Y-%m-%d")) # 将格式化时间 转化为 结构化时间
print("时间1",a)

b = time.strftime("%Y-%m-%d") # 获取当前的格式化时间
print("时间2",b)
d1 = datetime.date(a_s[0], a_s[1], a_s[2])
d2 = datetime.date(int(b.split("-")[0]), int(b.split("-")[1]), int(b.split("-")[2]))
print('时间2 - 时间1 的天数是:',(d2 - d1).days)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

输出

时间1 2022-9-1
时间2 2022-09-09
时间2 - 时间1 的天数是: 8
  • 1
  • 2
  • 3

致力于办公自动化的小小程序员一枚

都看到这了,关注+点赞+收藏=不迷路!!