Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Split days between 2 dates into batch of 30 or 31 and return the start date in each case

I want to get the start date of each month between 2 mentioned dates.

Like start date is 21st jan 2020 and end date is 30 oct 2020 I want the output to be in following format:

21 Jan 2020
31 jan 2020
1st feb 2020
28 feb 2020
1st march 2020
31st march 2020
.
.
.
.
1 st oct 2020
30 th oct 2020

How can we do this in python?

question from:https://stackoverflow.com/questions/65860543/split-days-between-2-dates-into-batch-of-30-or-31-and-return-the-start-date-in-e

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

1 Reply

0 votes
by (71.8m points)

Use dateutil module's rrule submodule for any kind of recurrence of date/time.

from dateutil import rrule, parser
start = parser.parse('Jan 21 2020')
end   = parser.parse('Oct 30 2020')
date_list = [start]
date_list.extend(list(rrule.rrule(rrule.MONTHLY, bymonthday=(-1,1), dtstart=start, until=end)))
date_list.append(end)
print(date_list)

Output-

[datetime.datetime(2020, 1, 21, 0, 0), datetime.datetime(2020, 1, 31, 0, 0), datetime.datetime(2020, 2, 1, 0, 0), datetime.datetime(2020, 2, 29, 0, 0), datetime.datetime(2020, 3, 1, 0, 0), datetime.datetime(2020, 3, 31, 0, 0), datetime.datetime(2020, 4, 1, 0, 0), datetime.datetime(2020, 4, 30, 0, 0), datetime.datetime(2020, 5, 1, 0, 0), datetime.datetime(2020, 5, 31, 0, 0), datetime.datetime(2020, 6, 1, 0, 0), datetime.datetime(2020, 6, 30, 0, 0), datetime.datetime(2020, 7, 1, 0, 0), datetime.datetime(2020, 7, 31, 0, 0), datetime.datetime(2020, 8, 1, 0, 0), datetime.datetime(2020, 8, 31, 0, 0), datetime.datetime(2020, 9, 1, 0, 0), datetime.datetime(2020, 9, 30, 0, 0), datetime.datetime(2020, 10, 1, 0, 0), datetime.datetime(2020, 10, 30, 0, 0)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...