SoFunction
Updated on 2024-10-29

Get the first and last day of each month in a given year using python

Search for keywords:

python get every first day of month

Refer to the answer:

Method I:

>>> import calendar
>>> (2002,1)
(1, 31)
>>> (2008,2)
(4, 29)
>>> (2100,2)
(0, 28)
 
>>> (2016, 2)[1]

Method II:

import datetime
for x in xrange(1, 13):
  dt_start = ((2016, x, 1)).strftime("%Y%m%d")
  if 12 == x:
    dt_end = ((2016, 12, 31)).strftime("%Y%m%d")
  else:
    dt_end = ((2016, x+1, 1) - (days = 1)).strftime("%Y%m%d")
  print dt_start, dt_end

Reference Links:

/questions/42950/get-last-day-of-the-month-in-python

/2/library/

/2/library/

/questions/22696662/python-list-of-first-day-of-month-for-given-period

summarize

Above is the entire content of this article, I hope that the content of this article for everyone to learn or use python can have some help, if there are questions you can leave a message to exchange.