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

yipeiwu_com6年前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能有一定的帮助,如果有疑问大家可以留言交流。

相关文章

Python3多线程版TCP端口扫描器

本文实例为大家分享了Python3多线程版TCP端口扫描器的具体代码,供大家参考,具体内容如下 使用命令 python BannerDemo.py -H 192.168.200.10...

安装Python的教程-Windows

安装Python的教程-Windows

在开始Python编程前,需要先安装Python环境。Python安装包可以到Python的官网下载,官网地址是https://www.python.org/,如果想直接跳过关于Pyth...

详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件

详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件

一、安装Pyinstaller 环境:python3.6、window10 注意事项: python64位版本打包的exe,只能在64位操作系统使用 打包文件夹和文件的名称不能用中文 p...

python多任务之协程的使用详解

1|0使用yield完成多任务 import time def test1(): while True: print("--1--") time.sleep(0.5)...

解决phantomjs截图失败,phantom.exit位置的问题

刚刚学习使用phantomjs,根据网上帖子自己手动改了一个延时截图功能,发现延时功能就是不能执行,最后一点点排查出了问题。 看代码: var page = require('web...