假设您有两个熊猫的日期时间:from_date
和end_date
。我需要一个函数将其拆分为n
个月的折叠数(让我们说n=3
)。例如:
import pandas as pd
from_date = pd.to_datetime("2020-02-15")
to_date = pd.to_datetime("2020-05-20")
应分为2折:
{
"1": {"from_date": 2020-02-15, "to_date": 2020-05-15},
"2": {"from_date": 2020-05-16, "to_date": 2020-05-20}
}
每折需要满足以下条件:
from_date + pd.DateOffset(months=2) >= end_date
。因此,这与开始日期和结束日期之间的天数无关。
最Python的方式是什么?熊猫里有东西吗?
答案 0 :(得分:0)
根据您希望使用两个日期的方式替换相应的打印语句!
根据How do I calculate the date six months from the current date using the datetime Python module?,dateutil.relativedelta
可以帮助解决有无第31天的那几个月!
import pandas as pd
from dateutil.relativedelta import relativedelta
from_date = pd.to_datetime("2020-02-15")
to_date = pd.to_datetime("2020-05-20")
fold = 0
result = {}
while from_date+relativedelta(months=+3)<to_date:
curfrom = from_date #retain current 'from_date'
from_date =from_date+relativedelta(months=+3)
result[fold] = {"from_date": curfrom, "to_date": from_date}
fold = fold+1
from_date = from_date + relativedelta(days=+1) #So that the next 'from_date' starts 1 day after
result[fold] = {"from_date": curfrom, "to_date": to_date}
print(result)
答案 1 :(得分:0)
我的解决方案:
import pandas as pd
def check_and_split(from_date, to_date):
from_date = pd.to_datetime(from_date)
to_date = pd.to_datetime(to_date)
done = False
fold = 0
result = {}
start = from_date
end = to_date
while not done:
if start + pd.DateOffset(months=2) > to_date:
done = True
end = to_date
else:
end = start + pd.DateOffset(months=3)
result[fold] = {"from_date": start, "to_date": end}
if not done:
start = end + pd.DateOffset(days=1)
fold += 1
return result
没有更Python化的方式吗?熊猫里有东西吗?