利用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 相关文章推荐
SublimeText 2编译python出错的解决方法(The system cannot find the file specified)
Nov 27 Python
python利用拉链法实现字典方法示例
Mar 25 Python
matplotlib在python上绘制3D散点图实例详解
Dec 09 Python
python使用xlrd和xlwt读写Excel文件的实例代码
Sep 05 Python
python实现zabbix发送短信脚本
Sep 17 Python
基于python-opencv3的图像显示和保存操作
Jun 27 Python
Django的models模型的具体使用
Jul 15 Python
python打印n位数“水仙花数”(实例代码)
Dec 25 Python
使用 Python 遍历目录树的方法
Feb 29 Python
python Protobuf定义消息类型知识点讲解
Mar 02 Python
python包的导入方式总结
Mar 02 Python
宝塔更新Python及Flask项目的部署
Apr 11 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调用mysql存储过程
2007/02/14 PHP
浅谈ThinkPHP的URL重写
2014/11/25 PHP
详解配置 Apache 服务器支持 PHP 文件的解析
2017/02/15 PHP
PHP中通过getopt解析GNU C风格命令行选项
2019/11/18 PHP
js类 from qq
2006/11/13 Javascript
firefox firebug中文入门教程 脚本之家新年特别版
2010/01/02 Javascript
Jquery中的CheckBox、RadioButton、DropDownList的取值赋值实现代码
2011/10/12 Javascript
JS 毫秒转时间示例代码
2013/09/22 Javascript
js实现省市联动效果的简单实例
2014/02/10 Javascript
深入理解JavaScript系列(37):设计模式之享元模式详解
2015/03/04 Javascript
JavaScript实现点击单选按钮改变输入框中文本域内容的方法
2015/08/12 Javascript
快速掌握Node.js事件驱动模型
2016/03/21 Javascript
个人网站留言页面(前端jQuery编写、后台php读写MySQL)
2016/05/03 Javascript
图解Javascript——作用域、作用域链、闭包
2017/03/21 Javascript
nodejs前端模板引擎swig入门详解
2018/05/15 NodeJs
JS/HTML5游戏常用算法之路径搜索算法 A*寻路算法完整实例
2018/12/14 Javascript
javascript定时器的简单应用示例【控制方块移动】
2019/06/17 Javascript
jquery插件开发模式实例详解
2019/07/20 jQuery
vue.js的状态管理vuex中store的使用详解
2019/11/08 Javascript
[03:49]DOTA2英雄基础教程 光之守卫
2014/01/14 DOTA
Python函数参数匹配模型通用规则keyword-only参数详解
2019/06/10 Python
django admin组件使用方法详解
2019/07/19 Python
Python发送邮件的实例代码讲解
2019/10/16 Python
使用Numpy对特征中的异常值进行替换及条件替换方式
2020/06/08 Python
Python如何读取、写入CSV数据
2020/07/28 Python
websocket+sockjs+stompjs详解及实例代码
2018/11/30 HTML / CSS
Philosophy美国官网:美国美容品牌
2016/08/15 全球购物
下述程序的作用是计算机数组中的最大元素值及其下标
2012/11/26 面试题
自荐信怎么写呢?
2013/12/09 职场文书
大学生村官心得体会范文
2014/01/04 职场文书
公司接待方案
2014/03/08 职场文书
博士生导师推荐信
2014/07/08 职场文书
医院我们的节日活动实施方案
2014/08/22 职场文书
作风建设年度心得体会
2014/10/29 职场文书
使用springMVC所需要的pom配置
2021/09/15 Java/Android
Python列表的索引与切片
2022/04/07 Python