利用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 用户登录验证的小例子
Mar 06 Python
在Python中使用第三方模块的教程
Apr 27 Python
Win8下python3.5.1安装教程
Jul 29 Python
django框架自定义用户表操作示例
Aug 07 Python
学习python可以干什么
Feb 26 Python
Python实现Mysql数据统计及numpy统计函数
Jul 15 Python
Python下opencv图像阈值处理的使用笔记
Aug 04 Python
python使用 request 发送表单数据操作示例
Sep 25 Python
详解Django配置优化方法
Nov 18 Python
vue学习笔记之动态组件和v-once指令简单示例
Feb 29 Python
Python处理mysql特殊字符的问题
Mar 02 Python
Python捕获异常堆栈信息的几种方法(小结)
May 18 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
thinkphp常见路径用法分析
2014/12/02 PHP
php利用递归实现删除文件目录的方法
2016/09/23 PHP
详解使用php-cs-fixer格式化代码
2020/09/16 PHP
Use Word to Search for Files
2007/06/15 Javascript
jQuery 可以拖动的div实现代码 脚本之家修正版
2009/06/26 Javascript
jQuery 表单验证扩展代码(二)
2010/10/20 Javascript
JS实现生成会变大变小的圆环实例
2015/08/05 Javascript
javascript实现在下拉列表中显示多级树形菜单的方法
2015/08/12 Javascript
js实现跨域访问的三种方法
2015/12/09 Javascript
javascript表单正则应用
2017/02/04 Javascript
JavaScript相等运算符的九条规则示例详解
2019/10/20 Javascript
[03:39]DOTA2英雄梦之声_第05期_幽鬼
2014/06/23 DOTA
Python与Java间Socket通信实例代码
2017/03/06 Python
基于django channel实现websocket的聊天室的方法示例
2019/04/11 Python
Python关键字及可变参数*args,**kw原理解析
2020/04/04 Python
python程序输出无内容的解决方式
2020/04/09 Python
python能自学吗
2020/06/18 Python
Abe’s of Maine:自1979以来销售相机和电子产品
2016/11/21 全球购物
马来西亚网上美容店:Hermo.my
2017/11/25 全球购物
捷克浴室和厨房设备购物网站:SIKO
2018/08/11 全球购物
写一个方法1000的阶乘
2012/11/21 面试题
AJAX应用和传统Web应用有什么不同
2013/08/24 面试题
政法大学毕业生自荐信范文
2014/01/01 职场文书
家长给小学生的评语
2014/01/30 职场文书
报关员个人职业生涯规划书
2014/03/12 职场文书
基督教婚礼主持词
2014/03/14 职场文书
公司副总经理任命书
2014/06/05 职场文书
4s店活动策划方案
2014/08/25 职场文书
银行委托书范本
2014/09/28 职场文书
学校运动会广播稿范文
2014/10/02 职场文书
搞笑婚前保证书
2015/02/28 职场文书
个人德育工作总结
2015/03/05 职场文书
公司表扬稿范文
2015/05/05 职场文书
大学开学感言
2015/08/01 职场文书
入党申请书格式
2019/06/20 职场文书
保安辞职申请书应该怎么写?
2019/07/15 职场文书