找到两个日期之间的月份的最佳方式 [英] Best way to find the months between two dates

查看:161
本文介绍了找到两个日期之间的月份的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast.

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对象。然后我循环添加一个星期到start datetime对象,并检查一个月的数值是否更大(除非该月是12月,那么它检查日期是否较少),如果该值较大我附加到列表几个月,并继续循环,直到我结束的日期。

So just to explain, what I'm doing here is taking the two dates and converting them from iso format into python datetime objects. Then I loop through adding a week to the start datetime object and check if the numerical value of the month is greater (unless the month is December then it checks if the date is less), If the value is greater I append it to the list of months and keep looping through until I get to my end date.

它的工作原理完全不是一个很好的方法...

It works perfectly it just doesn't seem like a good way of doing it...

推荐答案

如果添加一个星期,那么它将大约按需要工作4.35次。为什么不只是:

If adding by a week, then it will approximately do work 4.35 times the work as needed. Why not just:

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代码现在,没有测试,但我认为沿着同一行的想法将工作。

just pseduo code for now, haven't tested, but i think the idea along the same line will work.

这篇关于找到两个日期之间的月份的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆