Use python to obtain the first day and last day of each month in a year.

Source: Internet
Author: User

Use python to obtain the first day and last day of each month in a year.

Search Keyword:

python get every first day of month

Reference:

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 datetimefor 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 link:

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

Summary

The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.