近期,由于业务需要计算两个日期之前相差多少个月。我在网上找了很久,结果发现万能的python,居然没有一个模块计算两个日期的月数,像Java、C#之类的高级语言,都会有(date1-date2).months的现成方法,觉得不可思议。说句实在的,一直觉得python 的日期处理模块真心不好用。
哦,对了,别跟我说 datetime, calendar, dateutil 这些模块,因为我都试过了,都没用。有个竟然算出来还有错。datetime.timedelta只能计算出日时分秒。对年月却不支持。网上一搜,一大堆的。
dateutil.rrule这个例子是我好不容易找到的,请看我的测试结果:
1
2
3
4
5
6
7
8
9
10
|
import datetime from dateutil import rrule d1 = datetime.date( 2016 , 2 , 29 ) d2 = datetime.date( 2019 , 3 , 31 ) months = rrule.rrule(rrule.MONTHLY, dtstart = d1, until = d2).count() print (f "months={months}" ) |
看到这样的结果,我只能呵呵了。
废话不多少,献上自己写的代码:
该代码返回,(月,小数月)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
import datetime import calendar as c d1 = datetime.date( 2016 , 2 , 29 ) d2 = datetime.date( 2019 , 3 , 31 ) def calmonths(startdate, enddate): # 计算两个日期相隔月差 samemonthdate = None try : samemonthdate = datetime.date(enddate.year, enddate.month, startdate.day) except Exception as e: print (e) samemonthdate = datetime.date(enddate.year, enddate.month, c.monthrange(enddate.year, enddate.month)[ 1 ]) holdmonths = 0 decimalmonth = 0.0 if samemonthdate > enddate: premanthdate = None try : premanthdate = datetime.date(enddate.year, enddate.month - 1 , startdate.day) except Exception as e: print (e) premanthdate = datetime.date(enddate.year, enddate.month - 1 , c.monthrange( enddate.year, enddate.month - 1 )[ 1 ]) currmonthdays = (samemonthdate - premanthdate).days holdmonths = (premanthdate.year - startdate.year ) * 12 + premanthdate.month - startdate.month decimalmonth = (enddate - premanthdate).days / currmonthdays elif samemonthdate < enddate: nextmonthdate = None try : nextmonthdate = datetime.date(enddate.year, enddate.month + 1 , startdate.day) except Exception as e: nextmonthdate = datetime.date(enddate.year, enddate.month + 1 , c.monthrange( enddate.year, enddate.month + 1 )[ 1 ]) currmonthdays = (nextmonthdate - samemonthdate).days holdmonths = (samemonthdate.year - startdate.year ) * 12 + samemonthdate.month - startdate.month decimalmonth = (enddate - samemonthdate).days / currmonthdays else : holdmonths = (enddate.year - startdate.year ) * 12 + enddate.month - startdate.month return holdmonths, decimalmonth months = calmonths(d1, d2) print (f "months={months}" ) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/yicaifeitian/p/6895588.html