利用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程序与C程序的结合使用
Apr 07 Python
Python使用MONGODB入门实例
May 11 Python
python2 与python3的print区别小结
Jan 16 Python
python 编写简单网页服务器的实例
Jun 01 Python
Django2.1.3 中间件使用详解
Nov 26 Python
PyQt5 QTable插入图片并动态更新的实例
Jun 18 Python
python快速编写单行注释多行注释的方法
Jul 31 Python
使用Pandas的Series方法绘制图像教程
Dec 04 Python
解决python ThreadPoolExecutor 线程池中的异常捕获问题
Apr 08 Python
如何基于python实现不邻接植花
May 01 Python
Python读取JSON数据操作实例解析
May 18 Python
Django --Xadmin 判断登录者身份实例
Jul 03 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 数组遍历顺序理解
2009/09/09 PHP
PHP按行读取、处理较大CSV文件的代码实例
2014/04/09 PHP
基于递归实现的php树形菜单代码
2014/11/19 PHP
Javascript 中文字符串处理额外注意事项
2009/11/15 Javascript
Jquery之美中不足小结
2011/02/16 Javascript
Jquery 复选框取值兼容FF和IE8(测试有效)
2013/10/29 Javascript
面向对象设计模式的核心法则
2013/11/10 Javascript
js判断手机号运营商的方法
2015/10/23 Javascript
CSS中position属性之fixed实现div居中
2015/12/14 Javascript
基于jQuery实现带动画效果超炫酷的弹出对话框(附源码下载)
2016/02/22 Javascript
JavaScript自学笔记(必看篇)
2016/06/23 Javascript
BootStrap入门教程(一)之可视化布局
2016/09/19 Javascript
Angular的事件和表单详解
2016/12/26 Javascript
webpack进阶——缓存与独立打包的用法
2017/08/02 Javascript
nodejs中art-template模板语法的引入及冲突解决方案
2017/11/07 NodeJs
webstorm和.vue中es6语法报错的解决方法
2018/05/08 Javascript
vue 内置过滤器的使用总结(附加自定义过滤器)
2018/12/11 Javascript
jQuery移动端跑马灯抽奖特效升级版(抽奖概率固定)实现方法
2019/01/18 jQuery
vue+layui实现select动态加载后台数据的例子
2019/09/20 Javascript
vue动态合并单元格并添加小计合计功能示例
2020/11/26 Vue.js
[43:48]Ti4正赛第一天 VG vs NEWBEE 2
2014/07/19 DOTA
python使用正则表达式提取网页URL的方法
2015/05/26 Python
python 读文件,然后转化为矩阵的实例
2018/04/23 Python
Python3.遍历某文件夹提取特定文件名的实例
2018/04/26 Python
python实现播放音频和录音功能示例代码
2018/12/30 Python
Django实现简单网页弹出警告代码
2019/11/15 Python
Python3如何在Windows和Linux上打包
2020/02/25 Python
突袭HTML5之Javascript API扩展4—拖拽(Drag/Drop)概述
2013/01/31 HTML / CSS
澳大利亚领先的在线机械五金、园艺和存储专家:Edisons
2018/03/24 全球购物
财务总监岗位职责
2014/03/07 职场文书
医学专业大学生求职信
2014/07/12 职场文书
给病人的慰问信
2015/03/23 职场文书
教师岗位职责范本
2015/04/02 职场文书
2015年艾滋病防治工作总结
2015/05/22 职场文书
幼儿园春季开学通知
2015/07/16 职场文书
阳光体育运动标语口号
2015/12/26 职场文书