利用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解析xml模块封装代码
Feb 07 Python
Python中使用第三方库xlrd来写入Excel文件示例
Apr 05 Python
Python 12306抢火车票脚本
Feb 07 Python
python网络爬虫学习笔记(1)
Apr 09 Python
python 获取指定文件夹下所有文件名称并写入列表的实例
Apr 23 Python
关于Python的一些学习总结
May 25 Python
python shutil文件操作工具使用实例分析
Dec 25 Python
python类共享变量操作
Sep 03 Python
TensorFlow2.0使用keras训练模型的实现
Feb 20 Python
Python的Tqdm模块实现进度条配置
Feb 24 Python
Python爬虫爬取全球疫情数据并存储到mysql数据库的步骤
Mar 29 Python
Python FuzzyWuzzy实现模糊匹配
Apr 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 数据库树的遍历方法
2009/02/06 PHP
fleaphp crud操作之find函数的使用方法
2011/04/23 PHP
使用PHPCMS搭建wap手机网站
2015/09/20 PHP
jquery 仿QQ校友的DIV模拟窗口效果源码
2010/03/24 Javascript
jquery滚动组件(vticker.js)实现页面动态数据的滚动效果
2013/07/03 Javascript
JavaScript语言核心数据类型和变量使用介绍
2013/08/23 Javascript
js从10种颜色中随机取色实现每次取出不同的颜色
2013/10/23 Javascript
javascript 弹出的窗口返回值给父窗口具体实现
2013/11/23 Javascript
Jquery中offset()和position()的区别分析
2015/02/05 Javascript
js判断手机端(Android手机还是iPhone手机)
2015/07/22 Javascript
jQuery基于ajax()使用serialize()提交form数据的方法
2015/12/08 Javascript
使用BootStrap实现表格隔行变色及hover变色并在需要时出现滚动条
2017/01/04 Javascript
js图片轮播手动切换特效
2017/01/12 Javascript
Angularjs实现搜索关键字高亮显示效果
2017/01/17 Javascript
详解vue 中使用 AJAX获取数据的方法
2017/01/18 Javascript
JavaScript在form表单中使用button按钮实现submit提交方法
2017/01/23 Javascript
微信小程序获取音频时长与实时获取播放进度问题
2018/08/28 Javascript
React中获取数据的3种方法及优缺点
2020/02/18 Javascript
js实现3D旋转相册
2020/08/02 Javascript
vue实践---根据不同环境,自动转换请求的url地址操作
2020/09/21 Javascript
python实现旋转和水平翻转的方法
2018/10/25 Python
Python3利用Dlib实现摄像头实时人脸检测和平铺显示示例
2019/02/21 Python
详解python使用turtle库来画一朵花
2019/03/21 Python
python3.8 微信发送服务器监控报警消息代码实现
2019/11/05 Python
python_array[0][0]与array[0,0]的区别详解
2020/02/18 Python
canvas环形倒计时组件的示例代码
2018/06/14 HTML / CSS
英国航空官网:British Airways
2016/09/11 全球购物
假日旅行社实习自我鉴定
2013/09/24 职场文书
旅游管理专业学生求职信
2013/09/28 职场文书
毕业生动漫设计求职信
2013/10/11 职场文书
创业计划书怎样才能打动风投
2014/01/01 职场文书
长安大学毕业生自我鉴定
2014/01/17 职场文书
服务标语口号
2014/07/01 职场文书
小学体育教学随笔
2015/08/14 职场文书
Python中OpenCV实现简单车牌字符切割
2021/06/11 Python
sql server 累计求和实现代码
2022/02/28 SQL Server