利用python获取当前日期前后N天或N月日期的方法示例


Posted in Python onJuly 30, 2017

前言

最近因为工作原因,发现一个Python的时间组件,很好用分享出来!(忘记作者名字了,在这里先感谢了),下面话不多说,来一起看看详细的介绍吧。

示例代码:

# -*- coding: utf-8 -*-

'''获取当前日期前后N天或N月的日期'''

from time import strftime, localtime
from datetime import timedelta, date
import calendar

year = strftime("%Y", localtime())
mon = strftime("%m", localtime())
day = strftime("%d", localtime())
hour = strftime("%H", localtime())
min = strftime("%M", localtime())
sec = strftime("%S", localtime())

def today():
 '''''
 get today,date format="YYYY-MM-DD"
 '''''
 return date.today()


def todaystr():
 '''
 get date string, date format="YYYYMMDD"
 '''
 return year + mon + day


def datetime():
 '''''
 get datetime,format="YYYY-MM-DD HH:MM:SS"
 '''
 return strftime("%Y-%m-%d %H:%M:%S", localtime())


def datetimestr():
 '''''
 get datetime string
 date format="YYYYMMDDHHMMSS"
 '''
 return year + mon + day + hour + min + sec


def get_day_of_day(n=0):
 '''''
 if n>=0,date is larger than today
 if n<0,date is less than today
 date format = "YYYY-MM-DD"
 '''
 if (n < 0):
  n = abs(n)
  return date.today() - timedelta(days=n)
 else:
  return date.today() + timedelta(days=n)


def get_days_of_month(year, mon):
 '''''
 get days of month
 '''
 return calendar.monthrange(year, mon)[1]


def get_firstday_of_month(year, mon):
 '''''
 get the first day of month
 date format = "YYYY-MM-DD"
 '''
 days = "01"
 if (int(mon) < 10):
  mon = "0" + str(int(mon))
 arr = (year, mon, days)
 return "-".join("%s" % i for i in arr)


def get_lastday_of_month(year, mon):
 '''''
 get the last day of month
 date format = "YYYY-MM-DD"
 '''
 days = calendar.monthrange(year, mon)[1]
 mon = addzero(mon)
 arr = (year, mon, days)
 return "-".join("%s" % i for i in arr)


def get_firstday_month(n=0):
 '''''
 get the first day of month from today
 n is how many months
 '''
 (y, m, d) = getyearandmonth(n)
 d = "01"
 arr = (y, m, d)
 return "-".join("%s" % i for i in arr)


def get_lastday_month(n=0):
 '''''
 get the last day of month from today
 n is how many months
 '''
 return "-".join("%s" % i for i in getyearandmonth(n))


def getyearandmonth(n=0):
 '''''
 get the year,month,days from today
 befor or after n months
 '''
 thisyear = int(year)
 thismon = int(mon)
 totalmon = thismon + n
 if (n >= 0):
  if (totalmon <= 12):
   days = str(get_days_of_month(thisyear, totalmon))
   totalmon = addzero(totalmon)
   return (year, totalmon, days)
  else:
   i = totalmon / 12
   j = totalmon % 12
   if (j == 0):
    i -= 1
    j = 12
   thisyear += i
   days = str(get_days_of_month(thisyear, j))
   j = addzero(j)
   return (str(thisyear), str(j), days)
 else:
  if ((totalmon > 0) and (totalmon < 12)):
   days = str(get_days_of_month(thisyear, totalmon))
   totalmon = addzero(totalmon)
   return (year, totalmon, days)
  else:
   i = totalmon / 12
   j = totalmon % 12
   if (j == 0):
    i -= 1
    j = 12
   thisyear += i
   days = str(get_days_of_month(thisyear, j))
   j = addzero(j)
   return (str(thisyear), str(j), days)


def addzero(n):
 '''''
 add 0 before 0-9
 return 01-09
 '''
 nabs = abs(int(n))
 if (nabs < 10):
  return "0" + str(nabs)
 else:
  return nabs


def get_today_month(n=0):
 '''''
 获取当前日期前后N月的日期
 if n>0, 获取当前日期前N月的日期
 if n<0, 获取当前日期后N月的日期
 date format = "YYYY-MM-DD"
 '''
 (y, m, d) = getyearandmonth(n)
 arr = (y, m, d)
 if (int(day) < int(d)):
  arr = (y, m, day)
 return "-".join("%s" % i for i in arr)


if __name__ == "__main__":
 print today()
 print todaystr()
 print datetime()
 print datetimestr()
 print get_day_of_day(20)
 print get_day_of_day(-3)
 print get_today_month(-3)
 print get_today_month(3)
 print get_today_month(19)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持

Python 相关文章推荐
用Python编写脚本使IE实现代理上网的教程
Apr 23 Python
Python while、for、生成器、列表推导等语句的执行效率测试
Jun 03 Python
Python中enumerate函数代码解析
Oct 31 Python
安装python时MySQLdb报错的问题描述及解决方法
Mar 20 Python
在python win系统下 打开TXT文件的实例
Apr 29 Python
对python打乱数据集中X,y标签对的方法详解
Dec 14 Python
Python列表切片常用操作实例解析
Mar 10 Python
python中有函数重载吗
May 28 Python
Python的控制结构之For、While、If循环问题
Jun 30 Python
Python爬虫抓取论坛关键字过程解析
Oct 19 Python
在 Python 中使用 7zip 备份文件的操作
Dec 11 Python
Python采集爬取京东商品信息和评论并存入MySQL
Apr 12 Python
Python 装饰器使用详解
Jul 29 #Python
python实现数据图表
Jul 29 #Python
基于Python的XSS测试工具XSStrike使用方法
Jul 29 #Python
使用Kivy将python程序打包为apk文件
Jul 29 #Python
python对配置文件.ini进行增删改查操作的方法示例
Jul 28 #Python
Python3中使用PyMongo的方法详解
Jul 28 #Python
Python tkinter模块弹出窗口及传值回到主窗口操作详解
Jul 28 #Python
You might like
php中XMLHttpRequest(Ajax)不能设置自定义的Referer的解决方法
2011/11/26 PHP
php ci框架验证码实例分析
2013/06/26 PHP
详解使用php调用微信接口上传永久素材
2017/04/11 PHP
详谈PHP中public,private,protected,abstract等关键字的用法
2017/12/31 PHP
js客户端快捷键管理类的较完整实现和应用
2010/06/08 Javascript
javascript 函数及作用域总结介绍
2013/11/12 Javascript
jquery跟js初始化加载的多种方法及区别介绍
2014/04/02 Javascript
jquery 表单验证之通过 class验证表单不为空
2015/11/02 Javascript
jQuery实现的可编辑表格完整实例
2016/06/20 Javascript
jQuery通过ajax快速批量提交表单数据
2016/10/25 Javascript
Bootstrap基本样式学习笔记之表单(3)
2016/12/07 Javascript
详解vue 中使用 AJAX获取数据的方法
2017/01/18 Javascript
jQuery内容过滤选择器与子元素过滤选择器用法实例分析
2019/02/20 jQuery
JavaScript通如何过RGraph实现动态仪表盘
2020/10/15 Javascript
更改Python命令行交互提示符的方法
2015/01/14 Python
在Python中使用模块的教程
2015/04/27 Python
Python字符串处理之count()方法的使用
2015/05/18 Python
安装ElasticSearch搜索工具并配置Python驱动的方法
2015/12/22 Python
Python的mysql数据库的更新如何实现
2017/07/31 Python
Python基于csv模块实现读取与写入csv数据的方法
2018/01/18 Python
基于django channel实现websocket的聊天室的方法示例
2019/04/11 Python
深入了解如何基于Python读写Kafka
2019/12/31 Python
Python递归求出列表(包括列表中的子列表)的最大值实例
2020/02/27 Python
python文件操作seek()偏移量,读取指正到指定位置操作
2020/07/05 Python
html5的新增的标签和废除的标签简要概述
2013/02/20 HTML / CSS
英国知名奢侈品包包品牌:Milli Millu
2016/12/22 全球购物
名词解释WEB SERVICE,SOAP,UDDI,WSDL,JAXP,JAXM;JSWDL开发包的介绍。
2012/10/27 面试题
应届生的求职推荐信范文
2013/11/30 职场文书
快餐店的创业计划书范文
2014/01/29 职场文书
企业新年寄语
2014/04/04 职场文书
和睦家庭事迹
2014/05/14 职场文书
艺术节开幕词
2015/01/28 职场文书
工程服务质量承诺书
2015/04/29 职场文书
2019财务毕业实习报告
2019/06/27 职场文书
导游词之蜀山胜景瓦屋山
2019/11/29 职场文书
详解JSON.parse和JSON.stringify用法
2022/02/18 Javascript