Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

python - How to divide a date range into sets of 2 months with Pandas?

I'm trying to set up a logic that counts the number of months in a date range generated with pd.Timestamp. I'm able to get the number of months in the date, but I can't figure out how to use Pandas to then take the date range and divide it in sets of 2 months. For example: If date range is '2020-09-01' - '2021-01-01', it should return ['2020-09-01'-'2020-11-01', '2020-11-01' - '2021-01-01']. This is my code so far:

def get_installs_time(client, appId, startDate, endDate):
    startStamp = pd.Timestamp(startDate)
    endStamp = pd.Timestamp(endDate)
    months = (endStamp.to_period('M') - startStamp.to_period('M'))

In the case that the total months in the date range are 3, then the sets should be one of two months and the third month separately.

How can I build on this code and split the date range in sets of 2 months?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Still no answer? Here is something that is not pretty but does the job to cut the time range into chunks with a rest IF the start date is provided (as indicated) for the first of the month:

import pandas as pd

def get_installs_time(client, appId, startDate, endDate, blockLength):
    s = pd.date_range(start=startDate, end=endDate, freq=str(blockLength)+"MS", closed="left")
    e = (s[1:]-pd.to_timedelta(1, unit='D'))
    return list(zip(s.strftime('%Y-%m-%d').tolist(), e.strftime('%Y-%m-%d').tolist() + [endDate]))

print(get_installs_time("X", "Y", '2020-03-01', '2021-01-01', 3))

Sample output:

[('2020-03-01', '2020-05-31'), ('2020-06-01', '2020-08-31'), ('2020-09-01', '2020-11-30'), ('2020-12-01', '2021-01-01')]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...