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

相关文章

python logging日志模块以及多进程日志详解

本篇文章主要对 python logging 的介绍加深理解。更主要是 讨论在多进程环境下如何使用logging 来输出日志, 如何安全地切分日志文件。 1. logging日志模块介绍...

python Popen 获取输出,等待运行完成示例

我就废话不多说了,直接上代码吧! import subprocess def excuteCommand(com): ex = subprocess.Popen(com, std...

使用sklearn之LabelEncoder将Label标准化的方法

LabelEncoder可以将标签分配一个0—n_classes-1之间的编码 将各种标签分配一个可数的连续编号: >>> from sklearn import...

flask使用session保存登录状态及拦截未登录请求代码

本文主要研究的是flask使用session保存登录状态及拦截未登录请求的相关内容,具体介绍如下。 前端请求form: <form action="/user/add" met...

Python OpenCV对本地视频文件进行分帧保存的实例

如下所示: # coding=utf-8 import os import cv2 videos_src_path = "/home/wgp/视频/" video_forma...