Home > Article > Backend Development > Two ways to get the first and last day of each month in a year in Python
Search keywords:
python get every first day of month
Reference answer:
Method 1:
>>> import calendar >>> calendar.monthrange(2002,1) (1, 31) >>> calendar.monthrange(2008,2) (4, 29) >>> calendar.monthrange(2100,2) (0, 28) >>> calendar.monthrange(2016, 2)[1]
Method 2:
import datetime for x in xrange(1, 13): dt_start = (datetime.datetime(2016, x, 1)).strftime("%Y%m%d") if 12 == x: dt_end = (datetime.datetime(2016, 12, 31)).strftime("%Y%m%d") else: dt_end = (datetime.datetime(2016, x+1, 1) - datetime.timedelta(days = 1)).strftime("%Y%m%d") print dt_start, dt_end
Summary
The above is the entire content of this article. I hope the content of this article will be useful for everyone to learn or use python It can be of some help. If you have any questions, you can leave a message to communicate.
The above is the detailed content of Two ways to get the first and last day of each month in a year in Python. For more information, please follow other related articles on the PHP Chinese website!