查找两个日期之间的月份的最佳方法


91

我需要能够在python中准确找到两个日期之间的月份。我有一个可行的解决方案,但它不是很好(如优雅)或快速。

dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")]
months = [] 

tmpTime = dateRange[0]
oneWeek = timedelta(weeks=1)
tmpTime = tmpTime.replace(day=1)
dateRange[0] = tmpTime
dateRange[1] = dateRange[1].replace(day=1)
lastMonth = tmpTime.month
months.append(tmpTime)
while tmpTime < dateRange[1]:
    if lastMonth != 12:
        while tmpTime.month <= lastMonth:
            tmpTime += oneWeek
        tmpTime = tmpTime.replace(day=1)
        months.append(tmpTime)
        lastMonth = tmpTime.month

    else:
        while tmpTime.month >= lastMonth:
            tmpTime += oneWeek
        tmpTime = tmpTime.replace(day=1)
        months.append(tmpTime)
        lastMonth = tmpTime.month

因此,为了说明一下,我在这里所做的工作是获取两个日期并将其从iso格式转换为python datetime对象。然后,我在开始日期时间对象中添加一个星期,并检查月份的数值是否较大(除非月份为12月,否则它将检查日期是否较小),如果数值较大,则将其附加到列表中数月之久,一直循环播放,直到我到达结束日期为止。

它完美地工作,只是看起来不是一个好方法...


您是要问两个日期之间的月数,还是实际的月数是多少?
查尔斯·胡珀

在我的解决方案中:我没有增加“一个月的秒数”。我只是将数字1递增到2,然后从2递增到3。
极性

我只是想让您知道,即使您不喜欢我的答案,因为它“有一个循环”,您选择了具有两个循环的答案。列表理解仍然是循环。
查尔斯·胡珀

Answers:


0

更新二○一八年四月二十〇日:似乎OP @Joshkunz问了发现这几个月是两个日期之间,而不是“多少个月”是两个日期之间。所以我不确定为什么@JohnLaRooy被投票超过100次。@Joshkunz在原始问题下的评论中指出,他想要的是实际日期(或月份),而不是查找月份总数

所以,就出现希望的问题,因为两个日期之间2018-04-11,以2018-06-01

Apr 2018, May 2018, June 2018 

而如果它是什么之间2014-04-112018-06-01?那么答案将是

Apr 2014, May 2014, ..., Dec 2014, Jan 2015, ..., Jan 2018, ..., June 2018

这就是为什么很多年前我拥有以下伪代码的原因。它仅建议使用两个月作为终点并遍历它们,每次增加一个月。@Joshkunz提到他想要“月”,也提到他想要“日期”,在不确切知道的情况下,编写确切的代码很困难,但是想法是使用一个简单的循环遍历端点,并且一次增加一个月。

八年前的2010年的答案:

如果增加一周,那么它将大约完成所需工作量的4.35倍。为什么不只是:

1. get start date in array of integer, set it to i: [2008, 3, 12], 
       and change it to [2008, 3, 1]
2. get end date in array: [2010, 10, 26]
3. add the date to your result by parsing i
       increment the month in i
       if month is >= 13, then set it to 1, and increment the year by 1
   until either the year in i is > year in end_date, 
           or (year in i == year in end_date and month in i > month in end_date)

只是目前的pseduo代码,还没有测试,但是我认为同样的想法是可行的。


1
好的,如果增量是按月而不是几周完成的话,我会看到像2月这样的月份存在一些问题。
Joshkunz

我不能增加“一个月的秒数”。我只是将数字递增12,然后从递增23以后。
极性

194

首先定义一些测试用例,然后您将看到该函数非常简单并且不需要循环

from datetime import datetime

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month

assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12
assert diff_month(datetime(2010,10,1), datetime(2009,11,1)) == 11
assert diff_month(datetime(2010,10,1), datetime(2009,8,1)) == 14

您应该在问题中添加一些测试用例,因为有很多潜在的极端情况需要解决-定义两个日期之间的月数的方法不止一种。


2
它给出错误的结果。结果是介于“ 2015-04-30”和“ 2015-05-01”之间的1个月,实际上只是1天。

21
@饶 这就是为什么我说“定义两个日期之间的月数的方法不止一种”。这个问题仍然缺乏正式的定义。这也是为什么我建议在定义旁边提供测试用例的原因。
John La Rooy 2015年

2
我建议在减号周围添加abs(),以使d1小于d2:return abs(d1.year-d2.year)* 12 + abs(d1.month-d2.month)
Lukas Schulze

您确定@LukasSchulze吗?如果d1小于d2,则无论如何都要从第一个数字中减去该数字,对吗?
莉莉丝·埃丽娜

但是对于我来说,d1 <= d2或d2 <= d1并不重要。您只对diff感兴趣,无论两个日期中的哪个更小/更大。
卢卡斯·舒尔茨

40

一个班轮找到一个日期时间列表,该日期时间在两个日期之间按月递增。

import datetime
from dateutil.rrule import rrule, MONTHLY

strt_dt = datetime.date(2001,1,1)
end_dt = datetime.date(2005,6,1)

dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt, until=end_dt)]

这个!由于使用了rrule,因此可以适应许多特殊情况。请注意,输出值是日期时间,因此您可以将它们转换为所需的任何值(包括字符串)以匹配其他显示的内容。
Ezekiel Kruglick '16

当strt_dt为2001-1-29时,此操作将失败,因为该年没有Le日。
CS

2
OP要求提供开始日期和结束日期之间的月份列表。在我的示例中,使用您的方法错过了2月。当然,例如,仍然可以通过将开始日期调整为每月的第一天来挽救您的解决方案。
CS

2
这是一个很好的解决方案,它为我节省了很多时间。提供开始日期,可以使它变得更好[dt for dt in rrule(MONTHLY, bymonthday=10,dtstart=strt_dt, until=end_dt)]
赵鹏举

1
注意这一点。他们实际上在文档中有一条注释,指出rrule可能具有“例如当开始日期在月末时发生的令人惊讶的行为”(请参阅dateutil.readthedocs.io/en/stable/rrule.html中的Note)。避免这种情况的一种方法是在月份的第一天之前替换日期: start_date_first = start_date.replace(day=1), end_date_first = end_date.replace(day=1)然后rrule正确地计算月份。
Alla Sorokina

36

这对我有用-

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime('2011-08-15 12:00:00', '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime('2012-02-15', '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
r.months + (12*r.years)

删除不必要的 str()字符串文字。
jfs 2015年

7
不值得一提的是,如果增量超过1年,r.months将从0开始
jbkkd

2
通常我会做r.months *(r.years + 1),因为这会根据@jbkkd的意思进行调整
triunenature

9
@triunenature这看起来是错误的,肯定应该是r.months +(r.years * 12)
Moataz Elmasry

2
是的,如果日期相隔一年以上,这将不起作用。
HansG600

11

您可以使用dateutil模块中的rrule轻松计算得出:

from dateutil import rrule
from datetime import date

print(list(rrule.rrule(rrule.MONTHLY, dtstart=date(2013, 11, 1), until=date(2014, 2, 1))))

会给你:

 [datetime.datetime(2013, 11, 1, 0, 0),
 datetime.datetime(2013, 12, 1, 0, 0),
 datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 2, 1, 0, 0)]

10

获取结束月份(如果开始日期从2010年10月开始,则相对于开始月份的年月和月份,例如:2011年1月= 13),然后生成开始时间和该结束月份的日期时间,如下所示:

dt1, dt2 = dateRange
start_month=dt1.month
end_months=(dt2.year-dt1.year)*12 + dt2.month+1
dates=[datetime.datetime(year=yr, month=mn, day=1) for (yr, mn) in (
          ((m - 1) / 12 + dt1.year, (m - 1) % 12 + 1) for m in range(start_month, end_months)
      )]

如果两个日期都在同一年,则也可以简单地写为:

dates=[datetime.datetime(year=dt1.year, month=mn, day=1) for mn in range(dt1.month, dt2.month + 1)]

8

这篇文章钉!使用dateutil.relativedelta

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
r.months

1
@edouard在您给出的示例中您可以看到,日期是在不同的年份。但是,str()我所做的演员转换完全没有必要。
srodriguex16年

5
如果日期覆盖一年以上,则此方法不起作用,您需要添加relativedelta.relativedelta(date2, date1).years * 12
muon

delta.years*12 + delta.months
user2682863

7

我的简单解决方案:

import datetime

def months(d1, d2):
    return d1.month - d2.month + 12*(d1.year - d2.year)

d1 = datetime.datetime(2009, 9, 26)  
d2 = datetime.datetime(2019, 9, 26) 

print(months(d1, d2))

低估溶液
reabow

4

将“月”定义为1 / 12年,然后执行以下操作:

def month_diff(d1, d2): 
    """Return the number of months between d1 and d2, 
    such that d2 + month_diff(d1, d2) == d1
    """
    diff = (12 * d1.year + d1.month) - (12 * d2.year + d2.month)
    return diff

您可以尝试将一个月定义为“ 29、28、30或31天(取决于年份)的期间”。但是,如果您这样做,则还有一个要解决的问题。

尽管通常很清楚6月15 + 1个月应该是7月15 ,但是通常并不清楚1月30 + 1个月是2月还是3月。在后一种情况下,你可能被迫来计算日期为2月30日,那么“正确”它3月2日第二。但是,当你这样做,你会发现,3月2日第二 - 1个月显然是2月2日第二。Ergo,reducio ad abdurdum(此操作定义不明确)。


4

有一个基于360天年的简单解决方案,其中所有月份都为30天。它适合大多数用例,在给定两个日期的情况下,您需要计算整月数加上剩余天数。

from datetime import datetime, timedelta

def months_between(start_date, end_date):
    #Add 1 day to end date to solve different last days of month 
    s1, e1 = start_date , end_date  + timedelta(days=1)
    #Convert to 360 days
    s360 = (s1.year * 12 + s1.month) * 30 + s1.day
    e360 = (e1.year * 12 + e1.month) * 30 + e1.day
    #Count days between the two 360 dates and return tuple (months, days)
    return divmod(e360 - s360, 30)

print "Counting full and half months"
print months_between( datetime(2012, 01, 1), datetime(2012, 03, 31)) #3m
print months_between( datetime(2012, 01, 1), datetime(2012, 03, 15)) #2m 15d
print months_between( datetime(2012, 01, 16), datetime(2012, 03, 31)) #2m 15d
print months_between( datetime(2012, 01, 16), datetime(2012, 03, 15)) #2m
print "Adding +1d and -1d to 31 day month"
print months_between( datetime(2011, 12, 01), datetime(2011, 12, 31)) #1m 0d
print months_between( datetime(2011, 12, 02), datetime(2011, 12, 31)) #-1d => 29d
print months_between( datetime(2011, 12, 01), datetime(2011, 12, 30)) #30d => 1m
print "Adding +1d and -1d to 29 day month"
print months_between( datetime(2012, 02, 01), datetime(2012, 02, 29)) #1m 0d
print months_between( datetime(2012, 02, 02), datetime(2012, 02, 29)) #-1d => 29d
print months_between( datetime(2012, 02, 01), datetime(2012, 02, 28)) #28d
print "Every month has 30 days - 26/M to 5/M+1 always counts 10 days"
print months_between( datetime(2011, 02, 26), datetime(2011, 03, 05))
print months_between( datetime(2012, 02, 26), datetime(2012, 03, 05))
print months_between( datetime(2012, 03, 26), datetime(2012, 04, 05))

4

@ Vin-G有点美化了解决方案。

import datetime

def monthrange(start, finish):
  months = (finish.year - start.year) * 12 + finish.month + 1 
  for i in xrange(start.month, months):
    year  = (i - 1) / 12 + start.year 
    month = (i - 1) % 12 + 1
    yield datetime.date(year, month, 1)

4

您也可以使用箭头库。这是一个简单的示例:

from datetime import datetime
import arrow

start = datetime(2014, 1, 17)
end = datetime(2014, 6, 20)

for d in arrow.Arrow.range('month', start, end):
    print d.month, d.format('MMMM')

这将打印:

1 January
2 February
3 March
4 April
5 May
6 June

希望这可以帮助!


4
from dateutil import relativedelta

relativedelta.relativedelta(date1, date2)

months_difference = (r.years * 12) + r.months

3

尝试这样的事情。如果两个日期都在同一月份,则当前包括月份。

from datetime import datetime,timedelta

def months_between(start,end):
    months = []
    cursor = start

    while cursor <= end:
        if cursor.month not in months:
            months.append(cursor.month)
        cursor += timedelta(weeks=1)

    return months

输出如下:

>>> start = datetime.now() - timedelta(days=120)
>>> end = datetime.now()
>>> months_between(start,end)
[6, 7, 8, 9, 10]

不过,这仍然采用相同的循环方法,因此我不一定会看到好处……
Joshkunz 2010年

1
我看不出这是个问题。循环不是你的敌人。
查尔斯·胡珀

那么,每当它们是一个ajax查询时,都必须这样做。我知道循环并不是敌人,但看来循环是解决问题的缓慢方法,应该以一种更轻松的方式解决它。
Joshkunz


3

使用Pandas FWIW的方法如下:

import pandas as pd
pd.date_range("1990/04/03", "2014/12/31", freq="MS")

DatetimeIndex(['1990-05-01', '1990-06-01', '1990-07-01', '1990-08-01',
               '1990-09-01', '1990-10-01', '1990-11-01', '1990-12-01',
               '1991-01-01', '1991-02-01',
               ...
               '2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01',
               '2014-07-01', '2014-08-01', '2014-09-01', '2014-10-01',
               '2014-11-01', '2014-12-01'],
              dtype='datetime64[ns]', length=296, freq='MS')

请注意,它从给定开始日期之后的月份开始。


2

可以使用datetime.timedelta完成,其中可以通过calender.monthrange获得跳至下个月的天数。monthrange返回给定年份和月份的工作日(0-6〜周一至周日)和天数(28-31)。
例如:monthrange(2017,1)返回(6,31)。

这是使用此逻辑在两个月之间迭代的脚本。

from datetime import timedelta
import datetime as dt
from calendar import monthrange

def month_iterator(start_month, end_month):
    start_month = dt.datetime.strptime(start_month,
                                   '%Y-%m-%d').date().replace(day=1)
    end_month = dt.datetime.strptime(end_month,
                                 '%Y-%m-%d').date().replace(day=1)
    while start_month <= end_month:
        yield start_month
        start_month = start_month + timedelta(days=monthrange(start_month.year, 
                                                         start_month.month)[1])

`


您能否解释一下如何解决此问题?我们鼓励人们在答案中添加上下文;谢谢。
Gi0rgi0s

1
添加了解释
pankaj kumar

2

许多人已经给您很好的答案来解决此问题,但是我还没有阅读任何有关列表理解的文章,因此,我向您提供了类似用例的用法:


def compute_months(first_date, second_date):
    year1, month1, year2, month2 = map(
        int, 
        (first_date[:4], first_date[5:7], second_date[:4], second_date[5:7])
    )

    return [
        '{:0>4}-{:0>2}'.format(year, month)
        for year in range(year1, year2 + 1)
        for month in range(month1 if year == year1 else 1, month2 + 1 if year == year2 else 13)
    ]

>>> first_date = "2016-05"
>>> second_date = "2017-11"
>>> compute_months(first_date, second_date)
['2016-05',
 '2016-06',
 '2016-07',
 '2016-08',
 '2016-09',
 '2016-10',
 '2016-11',
 '2016-12',
 '2017-01',
 '2017-02',
 '2017-03',
 '2017-04',
 '2017-05',
 '2017-06',
 '2017-07',
 '2017-08',
 '2017-09',
 '2017-10',
 '2017-11']

1
#This definition gives an array of months between two dates.
import datetime
def MonthsBetweenDates(BeginDate, EndDate):
    firstyearmonths = [mn for mn in range(BeginDate.month, 13)]<p>
    lastyearmonths = [mn for mn in range(1, EndDate.month+1)]<p>
    months = [mn for mn in range(1, 13)]<p>
    numberofyearsbetween = EndDate.year - BeginDate.year - 1<p>
    return firstyearmonths + months * numberofyearsbetween + lastyearmonths<p>

#example
BD = datetime.datetime.strptime("2000-35", '%Y-%j')
ED = datetime.datetime.strptime("2004-200", '%Y-%j')
MonthsBetweenDates(BD, ED)

1

就像range函数一样,当月份为13时,转到下一年

def year_month_range(start_date, end_date):
    '''
    start_date: datetime.date(2015, 9, 1) or datetime.datetime
    end_date: datetime.date(2016, 3, 1) or datetime.datetime
    return: datetime.date list of 201509, 201510, 201511, 201512, 201601, 201602
    '''
    start, end = start_date.strftime('%Y%m'), end_date.strftime('%Y%m')
    assert len(start) == 6 and len(end) == 6
    start, end = int(start), int(end)

    year_month_list = []
    while start < end:
        year, month = divmod(start, 100)
        if month == 13:
            start += 88  # 201513 + 88 = 201601
            continue
        year_month_list.append(datetime.date(year, month, 1))

        start += 1
    return year_month_list

python shell中的示例

>>> import datetime
>>> s = datetime.date(2015,9,1)
>>> e = datetime.date(2016, 3, 1)
>>> year_month_set_range(s, e)
[datetime.date(2015, 11, 1), datetime.date(2015, 9, 1), datetime.date(2016, 1, 1), datetime.date(2016, 2, 1),
 datetime.date(2015, 12, 1), datetime.date(2015, 10, 1)]

1

通常90天并不是3个月的字面意思,仅是参考。

因此,最后,您需要检查天数是否大于15,以将+1加到月份计数器中。或更好的做法是,再添加一个半月计数器的Elif。

这个其他stackoverflow答案中,我终于结束了:

#/usr/bin/env python
# -*- coding: utf8 -*-

import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta
import calendar

start_date = datetime.date.today()
end_date = start_date + timedelta(days=111)
start_month = calendar.month_abbr[int(start_date.strftime("%m"))]

print str(start_date) + " to " + str(end_date)

months = relativedelta(end_date, start_date).months
days = relativedelta(end_date, start_date).days

print months, "months", days, "days"

if days > 16:
    months += 1

print "around " + str(months) + " months", "(",

for i in range(0, months):
    print calendar.month_abbr[int(start_date.strftime("%m"))],
    start_date = start_date + relativedelta(months=1)

print ")"

输出:

2016-02-29 2016-06-14
3 months 16 days
around 4 months ( Feb Mar Apr May )

我已经注意到,如果您添加的本年度剩余天数超过了该天数,那将是行不通的,这是意外的。


1

似乎答案不尽人意,此后我一直使用自己的代码,这更易于理解

from datetime import datetime
from dateutil import relativedelta

date1 = datetime.strptime(str('2017-01-01'), '%Y-%m-%d')
date2 = datetime.strptime(str('2019-03-19'), '%Y-%m-%d')

difference = relativedelta.relativedelta(date2, date1)
months = difference.months
years = difference.years
# add in the number of months (12) for difference in years
months += 12 * difference.years
months

1
from datetime import datetime
from dateutil import relativedelta

def get_months(d1, d2):
    date1 = datetime.strptime(str(d1), '%Y-%m-%d')
    date2 = datetime.strptime(str(d2), '%Y-%m-%d')
    print (date2, date1)
    r = relativedelta.relativedelta(date2, date1)
    months = r.months +  12 * r.years
    if r.days > 0:
        months += 1
    print (months)
    return  months


assert  get_months('2018-08-13','2019-06-19') == 11
assert  get_months('2018-01-01','2019-06-19') == 18
assert  get_months('2018-07-20','2019-06-19') == 11
assert  get_months('2018-07-18','2019-06-19') == 12
assert  get_months('2019-03-01','2019-06-19') == 4
assert  get_months('2019-03-20','2019-06-19') == 3
assert  get_months('2019-01-01','2019-06-19') == 6
assert  get_months('2018-09-09','2019-06-19') == 10

0

假设upperDate总是晚于lowerDate,并且它们都是datetime.date对象:

if lowerDate.year == upperDate.year:
    monthsInBetween = range( lowerDate.month + 1, upperDate.month )
elif upperDate.year > lowerDate.year:
    monthsInBetween = range( lowerDate.month + 1, 12 )
    for year in range( lowerDate.year + 1, upperDate.year ):
        monthsInBetween.extend( range(1,13) )
    monthsInBetween.extend( range( 1, upperDate.month ) )

我尚未对此进行彻底的测试,但看起来应该可以解决问题。


0

这是一个方法:

def months_between(start_dt, stop_dt):
    month_list = []
    total_months = 12*(stop_dt.year-start_dt.year)+(stop_dt.month-start_d.month)+1
    if total_months > 0:
        month_list=[ datetime.date(start_dt.year+int((start_dt+i-1)/12), 
                                   ((start_dt-1+i)%12)+1,
                                   1) for i in xrange(0,total_months) ]
    return month_list

这是首先计算两个日期(包括两个月)之间的总月数。然后,它以第一个日期为基数创建一个列表,并执行模算术以创建日期对象。


0

实际上我刚才需要做一些类似的事情

最后编写了一个函数,该函数返回一个表示两个日期之间的每个月的start和的元组列表,end因此我可以在其背面写一些SQL查询以获取每月销售总额等信息。

我相信有人知道自己在做什么,但希望能有所帮助的人可以改善它。

返回值如下(以今天为例-直到今天的365天为例)

[   (datetime.date(2013, 5, 1), datetime.date(2013, 5, 31)),
    (datetime.date(2013, 6, 1), datetime.date(2013, 6, 30)),
    (datetime.date(2013, 7, 1), datetime.date(2013, 7, 31)),
    (datetime.date(2013, 8, 1), datetime.date(2013, 8, 31)),
    (datetime.date(2013, 9, 1), datetime.date(2013, 9, 30)),
    (datetime.date(2013, 10, 1), datetime.date(2013, 10, 31)),
    (datetime.date(2013, 11, 1), datetime.date(2013, 11, 30)),
    (datetime.date(2013, 12, 1), datetime.date(2013, 12, 31)),
    (datetime.date(2014, 1, 1), datetime.date(2014, 1, 31)),
    (datetime.date(2014, 2, 1), datetime.date(2014, 2, 28)),
    (datetime.date(2014, 3, 1), datetime.date(2014, 3, 31)),
    (datetime.date(2014, 4, 1), datetime.date(2014, 4, 30)),
    (datetime.date(2014, 5, 1), datetime.date(2014, 5, 31))]

代码如下(有一些调试内容可以删除):

#! /usr/env/python
import datetime

def gen_month_ranges(start_date=None, end_date=None, debug=False):
    today = datetime.date.today()
    if not start_date: start_date = datetime.datetime.strptime(
        "{0}/01/01".format(today.year),"%Y/%m/%d").date()  # start of this year
    if not end_date: end_date = today
    if debug: print("Start: {0} | End {1}".format(start_date, end_date))

    # sense-check
    if end_date < start_date:
        print("Error. Start Date of {0} is greater than End Date of {1}?!".format(start_date, end_date))
        return None

    date_ranges = []  # list of tuples (month_start, month_end)

    current_year = start_date.year
    current_month = start_date.month

    while current_year <= end_date.year:
        next_month = current_month + 1
        next_year = current_year
        if next_month > 12:
            next_month = 1
            next_year = current_year + 1

        month_start = datetime.datetime.strptime(
            "{0}/{1}/01".format(current_year,
                                current_month),"%Y/%m/%d").date()  # start of month
        month_end = datetime.datetime.strptime(
            "{0}/{1}/01".format(next_year,
                                next_month),"%Y/%m/%d").date()  # start of next month
        month_end  = month_end+datetime.timedelta(days=-1)  # start of next month less one day

        range_tuple = (month_start, month_end)
        if debug: print("Month runs from {0} --> {1}".format(
            range_tuple[0], range_tuple[1]))
        date_ranges.append(range_tuple)

        if current_month == 12:
            current_month = 1
            current_year += 1
            if debug: print("End of year encountered, resetting months")
        else:
            current_month += 1
            if debug: print("Next iteration for {0}-{1}".format(
                current_year, current_month))

        if current_year == end_date.year and current_month > end_date.month:
            if debug: print("Final month encountered. Terminating loop")
            break

    return date_ranges


if __name__ == '__main__':
    print("Running in standalone mode. Debug set to True")
    from pprint import pprint
    pprint(gen_month_ranges(debug=True), indent=4)
    pprint(gen_month_ranges(start_date=datetime.date.today()+datetime.timedelta(days=-365),
                            debug=True), indent=4)

0

假设您想知道日期所在月份的“分数”(我已经做了),那么您需要做更多的工作。

from datetime import datetime, date
import calendar

def monthdiff(start_period, end_period, decimal_places = 2):
    if start_period > end_period:
        raise Exception('Start is after end')
    if start_period.year == end_period.year and start_period.month == end_period.month:
        days_in_month = calendar.monthrange(start_period.year, start_period.month)[1]
        days_to_charge = end_period.day - start_period.day+1
        diff = round(float(days_to_charge)/float(days_in_month), decimal_places)
        return diff
    months = 0
    # we have a start date within one month and not at the start, and an end date that is not
    # in the same month as the start date
    if start_period.day > 1:
        last_day_in_start_month = calendar.monthrange(start_period.year, start_period.month)[1]
        days_to_charge = last_day_in_start_month - start_period.day +1
        months = months + round(float(days_to_charge)/float(last_day_in_start_month), decimal_places)
        start_period = datetime(start_period.year, start_period.month+1, 1)

    last_day_in_last_month = calendar.monthrange(end_period.year, end_period.month)[1]
    if end_period.day != last_day_in_last_month:
        # we have lest days in the last month
        months = months + round(float(end_period.day) / float(last_day_in_last_month), decimal_places)
        last_day_in_previous_month = calendar.monthrange(end_period.year, end_period.month - 1)[1]
        end_period = datetime(end_period.year, end_period.month - 1, last_day_in_previous_month)

    #whatever happens, we now have a period of whole months to calculate the difference between

    if start_period != end_period:
        months = months + (end_period.year - start_period.year) * 12 + (end_period.month - start_period.month) + 1

    # just counter for any final decimal place manipulation
    diff = round(months, decimal_places)
    return diff

assert monthdiff(datetime(2015,1,1), datetime(2015,1,31)) == 1
assert monthdiff(datetime(2015,1,1), datetime(2015,02,01)) == 1.04
assert monthdiff(datetime(2014,1,1), datetime(2014,12,31)) == 12
assert monthdiff(datetime(2014,7,1), datetime(2015,06,30)) == 12
assert monthdiff(datetime(2015,1,10), datetime(2015,01,20)) == 0.35
assert monthdiff(datetime(2015,1,10), datetime(2015,02,20)) == 0.71 + 0.71
assert monthdiff(datetime(2015,1,31), datetime(2015,02,01)) == round(1.0/31.0,2) + round(1.0/28.0,2)
assert monthdiff(datetime(2013,1,31), datetime(2015,02,01)) == 12*2 + round(1.0/31.0,2) + round(1.0/28.0,2)

提供了一个示例,可以计算出两个日期(包括两个月)之间的月份数,包括该日期所在的每个月的分数。这意味着您可以计算出2015-01-20和2015-02-14之间的月份数,其中一月中日期的比例取决于一月中的天数;或同样考虑到2月的天数可以逐年变化。

供我参考,此代码也位于github- https: //gist.github.com/andrewyager/6b9284a4f1cdb1779b10


0

试试这个:

 dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"),
             datetime.strptime(dateRanges[1], "%Y-%m-%d")]
delta_time = max(dateRange) - min(dateRange)
#Need to use min(dateRange).month to account for different length month
#Note that timedelta returns a number of days
delta_datetime = (datetime(1, min(dateRange).month, 1) + delta_time -
                           timedelta(days=1)) #min y/m/d are 1
months = ((delta_datetime.year - 1) * 12 + delta_datetime.month -
          min(dateRange).month)
print months

您输入日期的顺序无关紧要,并且考虑了月份长度的差异。


请注意,这并不代表您的日期相同。如果delta_time.days = 0:months = 0,则其他方法最简单。
om_henners 2010年

0

这有效...

from datetime import datetime as dt
from dateutil.relativedelta import relativedelta
def number_of_months(d1, d2):
    months = 0
    r = relativedelta(d1,d2)
    if r.years==0:
        months = r.months
    if r.years>=1:
        months = 12*r.years+r.months
    return months
#example 
number_of_months(dt(2017,9,1),dt(2016,8,1))

0
from datetime import datetime

def diff_month(start_date,end_date):
    qty_month = ((end_date.year - start_date.year) * 12) + (end_date.month - start_date.month)

    d_days = end_date.day - start_date.day

    if d_days >= 0:
        adjust = 0
    else:
        adjust = -1
    qty_month += adjust

    return qty_month

diff_month(datetime.date.today(),datetime(2019,08,24))


#Examples:
#diff_month(datetime(2018,02,12),datetime(2019,08,24)) = 18
#diff_month(datetime(2018,02,12),datetime(2018,08,10)) = 5
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.