Get the first and last days of each month of a year using python

  • 2020-05-17 05:53:04
  • OfStack

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

Reference:

http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python

https://docs.python.org/2/library/calendar.html

https://docs.python.org/2/library/datetime.html

http://stackoverflow.com/questions/22696662/python-list-of-first-day-of-month-for-given-period

conclusion

The above is the whole content of this article, I hope the content of this article for everyone to learn or use python can have 1 definite help, if you have any questions, you can leave a message to communicate.


Related articles: