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

相关文章

PyQt5实现五子棋游戏(人机对弈)

PyQt5实现五子棋游戏(人机对弈)

这篇博客主要是为了学习Python和PyQt,因为对棋类游戏比较热衷,所以从规则较简单的五子棋入手,利用PyQt5实现图形界面,做一个可以进行人机对弈的脚本,最后打包成应用程序。AI的算...

python 实现图片旋转 上下左右 180度旋转的示例

如下所示: #首先建好一个数据_ud文件夹 import PIL.Image as img import os path_old = "C:/Users/49691/Desktop/...

对pandas处理json数据的方法详解

对pandas处理json数据的方法详解

今天展示一个利用pandas将json数据导入excel例子,主要利用的是pandas里的read_json函数将json数据转化为dataframe。 先拿出我要处理的json字符串:...

python+Django实现防止SQL注入的办法

先看看那种容易被注入的SQL id = 11001 sql = """ SELECT id, name, age FRO...

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

1 调试过程 用Python3.6+Sciter+PyCharm写了一个py测试脚本helloworld.py,该脚本中只含有一条语句“import sciter”。在PyCharm中运...