利用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 使用心得(九)解决No Python interpreter selected的问题
Jun 06 Python
深度剖析使用python抓取网页正文的源码
Jun 11 Python
Python多进程并发(multiprocessing)用法实例详解
Jun 02 Python
Python中的super()方法使用简介
Aug 14 Python
速记Python布尔值
Nov 09 Python
python实现字符串中字符分类及个数统计
Sep 28 Python
django开发post接口简单案例,获取参数值的方法
Dec 11 Python
Python(PyS60)实现简单语音整点报时
Nov 18 Python
Python Selenium安装及环境配置的实现
Mar 17 Python
Java如何基于wsimport调用wcf接口
Jun 17 Python
如何让python的运行速度得到提升
Jul 08 Python
python数字图像处理之图像的批量处理
Jun 28 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 攻击方法之谈php+mysql注射语句构造
2009/10/30 PHP
ubuntu下编译安装xcache for php5.3 的具体操作步骤
2013/06/18 PHP
老生常谈文本文件和二进制文件的区别
2017/02/27 PHP
PHP实现文件下载【实例分享】
2017/04/28 PHP
javascript 闭包
2011/09/15 Javascript
js遍历td tr等html元素
2012/12/13 Javascript
js将当前时间格式转换成时间搓(自写)
2013/09/26 Javascript
基于JQuery实现的Select级联
2014/01/27 Javascript
JQUERY实现网页右下角固定位置展开关闭特效的方法
2015/07/27 Javascript
浅谈js键盘事件全面控制
2016/12/01 Javascript
vue通过路由实现页面刷新的方法
2018/01/25 Javascript
微信小程序textarea层级过高(盖住其他元素)问题的解决办法
2019/03/04 Javascript
vue+element表格导出为Excel文件
2019/09/26 Javascript
微信小程序点击按钮动态切换input的disabled禁用/启用状态功能
2020/03/07 Javascript
jQuery实现点击滚动到指定元素上的方法分析
2020/03/19 jQuery
vue实现单一筛选、删除筛选条件
2020/10/26 Javascript
介绍Python中内置的itertools模块
2015/04/29 Python
Django中URL视图函数的一些高级概念介绍
2015/07/20 Python
Python的pycurl包用法简介
2015/11/13 Python
python中set常用操作汇总
2016/06/30 Python
Pandas中把dataframe转成array的方法
2018/04/13 Python
使用python实现http及ftp服务进行数据传输的方法
2018/10/26 Python
python同时遍历数组的索引和值的实例
2018/11/15 Python
对python tkinter窗口弹出置顶的方法详解
2019/06/14 Python
Python中生成一个指定长度的随机字符串实现示例
2019/11/06 Python
python 有效的括号的实现代码示例
2019/11/11 Python
CSS3关于z-index不生效问题的解决
2020/02/19 HTML / CSS
html5指南-5.使用web storage存储键值对的数据
2013/01/07 HTML / CSS
SIXPAD智能健身仪英国官网:革命性的训练装备品牌
2018/09/27 全球购物
莫斯科购买书籍网站:Book24
2020/01/12 全球购物
总经理司机职责
2014/02/02 职场文书
主持词开场白
2014/03/17 职场文书
遵纪守法演讲稿
2014/05/23 职场文书
幼儿园大班毕业评语
2014/12/31 职场文书
SpringCloud Alibaba 基本开发框架搭建过程
2021/06/13 Java/Android
关于Python中*args和**kwargs的深入理解
2021/08/07 Python