【Python】计算两个日期相差天数

时间:2025-02-10 07:53:01

解决方案

%m/%d/%Y

  • m表示月
  • d表示天
  • Y表示年

只要三个字母对应所给字符串的位置,即可正确计算。分隔符也可自定义,可以是%或-,也可以是其他字符

(1)举例一

import datetime
 
str1 ='4/3/2019' 
str2 ='4/3/2018'
date1=datetime.datetime.strptime(str1[0:10],"%m/%d/%Y")
date2=datetime.datetime.strptime(str2[0:10],"%m/%d/%Y")
num =(date1-date2).days

输出为365
(2)举例二

import datetime
 str1 = '2018-04-23'
 str2 = '2017-03-21'
 date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
 date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
 num=(date1-date2).days

输出398