利用python获取某年中每个月的第一天和最后一天

yipeiwu_com5年前Python基础

搜索关键字:

python get every first day of month

参考解答:

方法一:

>>> 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]

方法二:

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

参考链接:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流。

相关文章

使用Python下的XSLT API进行web开发的简单教程

使用Python下的XSLT API进行web开发的简单教程

Kafka 样式的 soap 端点 Christopher Dix 所开发的“Kafka — XSL SOAP 工具箱”(请参阅 参考资料)是一种用于构造 SOAP 端点的 XSLT 框...

python调用支付宝支付接口流程

python调用支付宝支付接口流程

项目演示: 一、输入金额 二、跳转到支付宝付款 三、支付成功 四、跳转回自己网站 在使用支付宝接口的前期准备: 1、支付宝公钥 2、应用公钥 3、应用私钥 4、APPID 5、D...

Python 中urls.py:URL dispatcher(路由配置文件)详解

Python 中urls.py:URL dispatcher(路由配置文件)详解

urls.py:URL dispatcher(路由配置文件) URL配置(URLconf)就像是Django所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的...

Python 中 -m 的典型用法、原理解析与发展演变

Python 中 -m 的典型用法、原理解析与发展演变

在命令行中使用 Python 时,它可以接收大约 20 个选项(option),语法格式如下: python [-bBdEhiIOqsSuvVWx?] [-c command...

利用python计算windows全盘文件md5值的脚本

利用python计算windows全盘文件md5值的脚本

import hashlib import os import time import configparser import uuid def test_file_md5(fi...