利用python获取当前日期前后N天或N月日期的方法示例

 更新时间:2017年07月30日 08:24:41   投稿:daisy  
最近在工作中遇到一个需求,查找资料发现了一个很好的时间组件,所以下面这篇文章主要给大家介绍了关于利用python获取当前日期前后N天或N月日期的方法示例,需要的朋友们可以参考借鉴,下面来一起看看吧。

前言

最近因为工作原因,发现一个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实现蚁群优化算法的示例代码

    蚁群算法是一种源于大自然生物世界的新的仿生进化算法,本文主要介绍了Python如何实现蚁群算法,文中通过示例代码具有一定的参考价值,感兴趣的小伙伴们可以了解一下
    2023-08-08
  • OpenCV 读取图像imread的使用详解

    OpenCV 读取图像imread的使用详解

    这篇文章主要介绍了OpenCV 读取图像imread的使用详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下
    2022-09-09
  • python实现合并两个数组的方法

    python实现合并两个数组的方法

    这篇文章主要介绍了python实现合并两个数组的方法,实例分析了两种常用的合并数组的技巧,非常简单实用,需要的朋友可以参考下
    2015-05-05
  • Python发送email的3种方法

    Python发送email的3种方法

    这篇文章主要介绍了Python发送email的3种方法,本文讲解了使用登录邮件服务器方法、调用sendmail命令、使用smtp服务来发送三种方法,需要的朋友可以参考下
    2015-04-04
  • Python使用defaultdict解决字典默认值

    Python使用defaultdict解决字典默认值

    本文主要介绍了Python使用defaultdict解决字典默认值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • matplotlib quiver箭图绘制案例

    matplotlib quiver箭图绘制案例

    这篇文章主要介绍了matplotlib quiver箭图绘制案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python 实现文件读写、坐标寻址、查找替换功能

    Python 实现文件读写、坐标寻址、查找替换功能

    这篇文章主要介绍了Python 实现文件读写、坐标寻址、查找替换功能,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2019-09-09
  • 利用python对月饼数据进行可视化(看看哪家最划算)

    利用python对月饼数据进行可视化(看看哪家最划算)

    通过python对数据进行可视化展示,可直观地展示数据之间的关系,为用户提供更多的信息,这篇文章主要给大家介绍了关于利用python对月饼数据进行可视化的相关资料,看看哪家最划算,需要的朋友可以参考下
    2022-09-09
  • 浅析Python中常见数据脱敏技术应用与对比

    浅析Python中常见数据脱敏技术应用与对比

    数据脱敏通过对敏感数据进行转换,确保其在保护隐私的同时仍能用于开发,本文为大家整理了一些常见的数据脱敏技术,感兴趣的小伙伴可以了解下
    2025-02-02
  • Python格式化输出之format用法详解

    Python格式化输出之format用法详解

    Python中格式化字符串目前有两种阵营:%和format,这篇文章主要给大家介绍了关于Python格式化输出之format用法的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-01-01

最新评论