利用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 getopt 参数处理小示例
Jun 09 Python
python使用fileinput模块实现逐行读取文件的方法
Apr 29 Python
深入解析Python编程中super关键字的用法
Jun 24 Python
python解决Fedora解压zip时中文乱码的方法
Sep 18 Python
python使用TensorFlow进行图像处理的方法
Feb 28 Python
浅谈Django的缓存机制
Aug 23 Python
python实现连连看辅助之图像识别延伸
Jul 17 Python
基于python plotly交互式图表大全
Dec 07 Python
解决Python图形界面中设置尺寸的问题
Mar 05 Python
Python使用进程Process模块管理资源
Mar 05 Python
10个python爬虫入门实例(小结)
Nov 01 Python
Python如何利用pandas读取csv数据并绘图
Jul 07 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
模仿OSO的论坛(一)
2006/10/09 PHP
php实现的支持断点续传的文件下载类
2014/09/23 PHP
php中使用Ajax时出现Error(c00ce56e)的详细解决方案
2014/11/03 PHP
谈谈 PHP7新增功能
2015/12/16 PHP
javascript 触发事件列表 比较不错
2009/09/03 Javascript
兼容IE与firefox火狐的回车事件(js与jquery)
2010/10/20 Javascript
EditPlus注册码生成器(js代码实现)
2013/03/25 Javascript
js加载之使用DOM方法动态加载Javascript文件
2013/11/08 Javascript
Jquery性能优化详解
2014/05/15 Javascript
node.js中的fs.mkdirSync方法使用说明
2014/12/17 Javascript
ajax读取数据后使用jqchart显示图表的方法
2015/06/10 Javascript
javascript实现状态栏中文字动态显示的方法
2015/10/20 Javascript
Vuejs第十一篇组件之slot内容分发实例详解
2016/09/09 Javascript
快速掌握jQuery插件开发
2017/01/19 Javascript
JavaScript实现跟随滚动缓冲运动广告框
2017/07/15 Javascript
快速搭建React的环境步骤详解
2017/11/06 Javascript
浅谈Node.js 子进程与应用场景
2018/01/24 Javascript
JS实现常见的查找、排序、去重算法示例
2018/05/21 Javascript
vue和webpack打包项目相对路径修改的方法
2018/06/15 Javascript
Vue实现美团app的影院推荐选座功能【推荐】
2018/08/29 Javascript
layui table 表格模板按钮的实例代码
2019/09/21 Javascript
JavaScript事件循环及宏任务微任务原理解析
2020/09/02 Javascript
python实现定时自动备份文件到其他主机的实例代码
2018/02/23 Python
Python Selenium Cookie 绕过验证码实现登录示例代码
2018/04/10 Python
Python之dict(或对象)与json之间的互相转化实例
2018/06/05 Python
python跳过第一行快速读取文件内容的实例
2018/07/12 Python
python使用folium库绘制地图点击框
2018/09/21 Python
Python Des加密解密如何实现软件注册码机器码
2020/01/08 Python
意大利巧克力店:Chocolate Shop
2019/07/24 全球购物
酒店工作职员求职简历的自我评价
2013/10/23 职场文书
初中国旗下的演讲稿
2014/08/28 职场文书
学习雷锋精神活动总结
2015/02/06 职场文书
结婚堵门保证书
2015/05/08 职场文书
考教师资格证不要错过的4个最佳时机
2019/07/17 职场文书
导游词之茶卡盐湖
2019/11/26 职场文书
golang 实现菜单树的生成方式
2021/04/28 Golang