利用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 pickle 和 shelve模块的用法
Sep 16 Python
Python处理RSS、ATOM模块FEEDPARSER介绍
Feb 18 Python
详细介绍Python中的偏函数
Apr 27 Python
pandas对dataFrame中某一个列的数据进行处理的方法
Jul 08 Python
利用Pandas和Numpy按时间戳将数据以Groupby方式分组
Jul 22 Python
Django中使用session保持用户登陆连接的例子
Aug 06 Python
python 定时器每天就执行一次的实现代码
Aug 14 Python
基于Python实现签到脚本过程解析
Oct 25 Python
简单了解python filter、map、reduce的区别
Jan 14 Python
Python模拟FTP文件服务器的操作方法
Feb 18 Python
django美化后台django-suit的安装配置操作
Jul 12 Python
Selenium 安装和简单使用的实现
Dec 04 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 IE中下载附件问题解决方法
2014/01/07 PHP
php实现的常见排序算法汇总
2014/09/08 PHP
php生成短域名函数
2015/03/23 PHP
Symfony2实现从数据库获取数据的方法小结
2016/03/18 PHP
php nginx 实时输出的简单实现方法
2018/01/21 PHP
thinkphp5使用无限极分类
2019/02/18 PHP
laravel 事件/监听器实例代码
2019/04/12 PHP
JS URL传中文参数引发的乱码问题
2009/09/02 Javascript
javascript,jquery闭包概念分析
2010/06/19 Javascript
js 中 document.createEvent的用法
2010/08/29 Javascript
捕获和分析JavaScript Error的方法
2014/03/25 Javascript
JavaScript中连接操作Oracle数据库实例
2015/04/02 Javascript
关于input全选反选恶心的异常情况
2016/07/24 Javascript
AngularJS入门教程之迭代器过滤详解
2016/08/18 Javascript
微信小程序图片宽100%显示并且不变形
2017/06/21 Javascript
JS 组件系列之Bootstrap Table的冻结列功能彻底解决高度问题
2017/06/30 Javascript
详解Node.js一行命令上传本地文件到服务器
2019/04/22 Javascript
详解微信小程序调用支付接口支付
2019/04/28 Javascript
[40:56]2018DOTA2亚洲邀请赛 3.31 小组赛 A组 Liquid vs TNC
2018/04/01 DOTA
使用Mixin设计模式进行Python编程的方法讲解
2016/06/21 Python
Python3中关于cookie的创建与保存
2018/10/21 Python
Python实现简单的2048小游戏
2021/03/01 Python
详解HTML5表单新增属性
2016/12/21 HTML / CSS
浅析数据存储的三种方式 cookie sessionstorage localstorage 的异同
2020/06/04 HTML / CSS
工程业务员岗位职责
2013/12/31 职场文书
企业标语口号
2014/06/10 职场文书
部门活动策划方案
2014/08/16 职场文书
企业委托书范本
2014/09/13 职场文书
2014年党员自我评议对照检查材料
2014/09/20 职场文书
2014年党员整改措施范文
2014/09/21 职场文书
儿园租房协议书范本
2014/12/02 职场文书
安全保证书怎么写
2015/02/28 职场文书
观后感格式
2015/06/19 职场文书
再读《皇帝的新衣》的读后感悟!
2019/08/07 职场文书
Python 使用dict实现switch的操作
2021/04/07 Python
Windows server 2012 R2 安装IIS服务器
2022/04/29 Servers