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
183 views
in Technique[技术] by (71.8m points)

python - How to get all days in current month?

I want to get all datetime object of each day in the current month but I haven't done yet. The result expected I wanted:

[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), 
 datetime.date(2014, 1, 3), ..., datetime.date(2014, 1, 29),
 datetime.date(2014, 1, 30), datetime.date(2014, 1, 31)]

How can I solve this issue?

Please show me your ideas or suggestions. Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a solution with datetime and calendar:

>>> import datetime, calendar
>>> year = 2014
>>> month = 1
>>> num_days = calendar.monthrange(year, month)[1]
>>> days = [datetime.date(year, month, day) for day in range(1, num_days+1)]
>>> days
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5), datetime.date(2014, 1, 6), datetime.date(2014, 1, 7), datetime.date(2014, 1, 8), datetime.date(2014, 1, 9), datetime.date(2014, 1, 10), datetime.date(2014, 1, 11), datetime.date(2014, 1, 12), datetime.date(2014, 1, 13), datetime.date(2014, 1, 14), datetime.date(2014, 1, 15), datetime.date(2014, 1, 16), datetime.date(2014, 1, 17), datetime.date(2014, 1, 18), datetime.date(2014, 1, 19), datetime.date(2014, 1, 20), datetime.date(2014, 1, 21), datetime.date(2014, 1, 22), datetime.date(2014, 1, 23), datetime.date(2014, 1, 24), datetime.date(2014, 1, 25), datetime.date(2014, 1, 26), datetime.date(2014, 1, 27), datetime.date(2014, 1, 28), datetime.date(2014, 1, 29), datetime.date(2014, 1, 30), datetime.date(2014, 1, 31)]

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

...