Home > Backend Development > Python Tutorial > Two ways to get the first and last day of each month in a year in Python

Two ways to get the first and last day of each month in a year in Python

高洛峰
Release: 2017-03-24 17:46:41
Original
3809 people have browsed it

Search keywords:

python get every first day of month
Copy after login


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]
Copy after login


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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template