利用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装饰器深入学习

什么是装饰器 在我们的软件产品升级时,常常需要给各个函数新增功能,而在我们的软件产品中,相同的函数可能会被调用上百次,这种情况是很常见的,如果我们一个个的修改,那我们的码农岂不要挂掉了(...

Python 实现引用其他.py文件中的类和类的方法

#HelloWorld是文件名称,Hello是类 from HelloWorld import Hello 调用,Hello类的方法: >>> h = Hel...

python打印异常信息的两种实现方式

1. 直接打印错误 try: # your code except KeyboardInterrupt: print("quit") except Excepti...

Python将图片批量从png格式转换至WebP格式

Python将图片批量从png格式转换至WebP格式

实现效果 将位于/img目录下的1000张.png图片,转换成.webp格式,并存放于img_webp文件夹内。 源图片目录 目标图片目录 关于批量生成1000张图片,可以参考这篇文...

python中常用的各种数据库操作模块和连接实例

工作中,经常会有用python访问各种数据库的需求,比如从oracle读点配置文件或者往mysql写点结果信息之类的。这里列一下可能用到的各个模块。 sqlite3: 内置模块用sqli...