-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonthscalculation.py
62 lines (54 loc) · 2.11 KB
/
monthscalculation.py
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
import datetime
import calendar as c
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
if enddate.month == 12:
endyear = enddate.year + 1
endmonth = 1
else:
endyear = enddate.year
endmonth = enddate.month + 1
try:
nextmonthdate = datetime.date(
enddate.year, enddate.month + 1, startdate.day)
except Exception as e:
nextmonthdate = datetime.date(
endyear, endmonth, c.monthrange(endyear, endmonth)[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
if __name__ == '__main__':
d1 = datetime.date(2021, 1, 1)
d2 = datetime.date(2022, 1, 1)
months = calmonths(d1, d2)
print(f"months={months}")