利用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 相关文章推荐
pycharm 使用心得(六)进行简单的数据库管理
Jun 06 Python
简单的Apache+FastCGI+Django配置指南
Jul 22 Python
在windows下快速搭建web.py开发框架方法
Apr 22 Python
Python 如何访问外围作用域中的变量
Sep 11 Python
分析Python中解析构建数据知识
Jan 20 Python
Python基于hashlib模块的文件MD5一致性加密验证示例
Feb 10 Python
Python  unittest单元测试框架的使用
Sep 08 Python
Python用5行代码写一个自定义简单二维码
Oct 21 Python
将python图片转为二进制文本的实例
Jan 24 Python
PyCharm安装Markdown插件的两种方法
Jun 24 Python
使用 Django Highcharts 实现数据可视化过程解析
Jul 31 Python
Python偏函数实现原理及应用
Nov 20 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
一个SQL管理员的web接口
2006/10/09 PHP
dedecms 批量提取第一张图片最为缩略图的代码(文章+软件)
2009/10/29 PHP
PHP写的资源下载防盗链类分享
2014/05/12 PHP
CentOS 6.3下安装PHP xcache扩展模块笔记
2014/09/10 PHP
分享3个php获取日历的函数
2015/09/25 PHP
PHP中substr函数字符串截取用法分析
2016/01/07 PHP
PHP连接sftp并下载文件的方法教程
2018/08/26 PHP
jQuery中:focus选择器用法实例
2014/12/30 Javascript
javascript中传统事件与现代事件
2015/06/23 Javascript
javascript创建cookie、读取cookie
2016/03/31 Javascript
微信小程序商城项目之侧栏分类效果(1)
2017/04/17 Javascript
vue中七牛插件使用的实例代码
2017/07/28 Javascript
VueJs组件prop验证简单介绍
2017/09/12 Javascript
Nodejs下使用gm圆形裁剪并合成图片的示例
2018/02/22 NodeJs
async/await优雅的错误处理方法总结
2019/01/30 Javascript
vant组件中 dialog的确认按钮的回调事件操作
2020/11/04 Javascript
javascript实现点击产生随机图形
2021/01/25 Javascript
Python multiprocessing.Manager介绍和实例(进程间共享数据)
2014/11/21 Python
用实例解释Python中的继承和多态的概念
2015/04/27 Python
使用python实现rsa算法代码
2016/02/17 Python
CentOS下使用yum安装python-pip失败的完美解决方法
2017/08/16 Python
Python实现的单向循环链表功能示例
2017/11/10 Python
Python自定义线程类简单示例
2018/03/23 Python
Python中新式类与经典类的区别详析
2019/07/10 Python
django创建简单的页面响应实例教程
2019/09/06 Python
Python Django模板之模板过滤器与自定义模板过滤器示例
2019/10/18 Python
python3中布局背景颜色代码分析
2020/12/01 Python
FOREO官方网站:LUNA露娜洁面仪
2016/11/28 全球购物
印度首个本地在线平台:nearbuy
2019/03/28 全球购物
什么是Linux虚拟文件系统VFS
2015/08/25 面试题
ruby如何进行集成操作?Ruby能进行多重继承吗?
2013/10/16 面试题
应届生保险求职信
2013/11/11 职场文书
艺术应用与设计专业个人的自我评价
2013/11/19 职场文书
自动一体化专业求职信
2014/03/15 职场文书
领导离职感言
2015/08/03 职场文书
创业计划书之冷饮店
2019/09/27 职场文书