利用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 回调函数和回调方法的实现分析
Mar 23 Python
TensorFlow高效读取数据的方法示例
Feb 06 Python
python3+PyQt5实现自定义窗口部件Counters
Apr 20 Python
python dataframe 输出结果整行显示的方法
Jun 14 Python
Numpy之文件存取的示例代码
Aug 03 Python
基于Python对数据shape的常见操作详解
Dec 25 Python
在Python函数中输入任意数量参数的实例
Jul 16 Python
Flask框架学习笔记之模板操作实例详解
Aug 15 Python
python安装本地whl的实例步骤
Oct 12 Python
Python基于wordcloud及jieba实现中国地图词云图
Jun 09 Python
利用python汇总统计多张Excel
Sep 22 Python
Python3 如何开启自带http服务
May 18 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 filter_var() 函数 Filter 函数
2012/04/25 PHP
通过PHP current函数获取未知字符键名数组第一个元素的值
2013/06/24 PHP
PHP_SELF,SCRIPT_NAME,REQUEST_URI区别
2014/12/24 PHP
php采用session实现防止页面重复刷新
2015/12/24 PHP
Yii2.0中的COOKIE和SESSION用法
2016/08/12 PHP
使用jscript实现二进制读写脚本代码
2008/06/09 Javascript
JavaScript 盒模型 尺寸深入理解
2012/12/31 Javascript
解决jquery1.9不支持browser对象的问题
2013/11/13 Javascript
把文本中的URL地址转换为可点击链接的JavaScript、PHP自定义函数
2014/07/29 Javascript
node.js中的http.response.removeHeader方法使用说明
2014/12/14 Javascript
超级简单的jquery操作表格方法
2014/12/15 Javascript
浅谈js中对象的使用
2016/08/11 Javascript
jQuery窗口拖动功能的实现代码
2017/02/04 Javascript
Node.JS中快速扫描端口并发现局域网内的Web服务器地址(80)
2017/09/18 Javascript
axios封装,使用拦截器统一处理接口,超详细的教程(推荐)
2019/05/02 Javascript
javascript面向对象三大特征之封装实例详解
2019/07/24 Javascript
vue+axios实现post文件下载
2019/09/25 Javascript
9种方法优化jQuery代码详解
2020/02/04 jQuery
JavaScript中跨域问题的深入理解
2021/03/04 Javascript
python映射列表实例分析
2015/01/26 Python
django之常用命令详解
2016/06/30 Python
Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)
2017/05/08 Python
python安装Scrapy图文教程
2017/08/14 Python
Python如何读写CSV文件
2020/08/13 Python
浅谈css3中的渐进增强和优雅降级
2017/12/01 HTML / CSS
八一建军节部队活动方案
2014/02/04 职场文书
创业资金计划书
2014/02/06 职场文书
2014乡镇党政班子四风问题思想汇报
2014/09/14 职场文书
见习报告格式要求
2014/11/04 职场文书
学生个人评语大全
2015/01/04 职场文书
办公室岗位职责
2015/02/04 职场文书
2015年世界环境日活动总结
2015/02/11 职场文书
讲座开场白台词和结束语
2015/05/29 职场文书
MySQL系列之九 mysql查询缓存及索引
2021/07/02 MySQL
解决Oracle数据库用户密码过期
2022/05/11 Oracle
git中cherry-pick命令的使用教程
2022/06/25 Servers