【python】python获取当前日期前后N天或N月的日期

  1 # -*- coding: utf-8 -*-
  2
  3 ‘‘‘获取当前日期前后N天或N月的日期‘‘‘
  4
  5 from time import strftime, localtime
  6 from datetime import timedelta, date
  7 import calendar
  8
  9 year = strftime("%Y",localtime())
 10 mon  = strftime("%m",localtime())
 11 day  = strftime("%d",localtime())
 12 hour = strftime("%H",localtime())
 13 min  = strftime("%M",localtime())
 14 sec  = strftime("%S",localtime())
 15
 16 def today():
 17     ‘‘‘‘‘
 18     get today,date format="YYYY-MM-DD"
 19     ‘‘‘‘‘
 20     return date.today()
 21
 22 def todaystr():
 23     ‘‘‘
 24     get date string, date format="YYYYMMDD"
 25     ‘‘‘
 26     return year+mon+day
 27
 28 def datetime():
 29     ‘‘‘‘‘
 30     get datetime,format="YYYY-MM-DD HH:MM:SS"
 31     ‘‘‘
 32     return strftime("%Y-%m-%d %H:%M:%S",localtime())
 33
 34 def datetimestr():
 35     ‘‘‘‘‘
 36     get datetime string
 37     date format="YYYYMMDDHHMMSS"
 38     ‘‘‘
 39     return year+mon+day+hour+min+sec
 40
 41 def get_day_of_day(n=0):
 42     ‘‘‘‘‘
 43     if n>=0,date is larger than today
 44     if n<0,date is less than today
 45     date format = "YYYY-MM-DD"
 46     ‘‘‘
 47     if(n<0):
 48         n = abs(n)
 49         return date.today()-timedelta(days=n)
 50     else:
 51         return date.today()+timedelta(days=n)
 52
 53 def get_days_of_month(year,mon):
 54     ‘‘‘‘‘
 55     get days of month
 56     ‘‘‘
 57     return calendar.monthrange(year, mon)[1]
 58
 59 def get_firstday_of_month(year,mon):
 60     ‘‘‘‘‘
 61     get the first day of month
 62     date format = "YYYY-MM-DD"
 63     ‘‘‘
 64     days="01"
 65     if(int(mon)<10):
 66         mon = "0"+str(int(mon))
 67     arr = (year,mon,days)
 68     return "-".join("%s" %i for i in arr)
 69
 70 def get_lastday_of_month(year,mon):
 71     ‘‘‘‘‘
 72     get the last day of month
 73     date format = "YYYY-MM-DD"
 74     ‘‘‘
 75     days=calendar.monthrange(year, mon)[1]
 76     mon = addzero(mon)
 77     arr = (year,mon,days)
 78     return "-".join("%s" %i for i in arr)
 79
 80 def get_firstday_month(n=0):
 81     ‘‘‘‘‘
 82     get the first day of month from today
 83     n is how many months
 84     ‘‘‘
 85     (y,m,d) = getyearandmonth(n)
 86     d = "01"
 87     arr = (y,m,d)
 88     return "-".join("%s" %i for i in arr)
 89
 90 def get_lastday_month(n=0):
 91     ‘‘‘‘‘
 92     get the last day of month from today
 93     n is how many months
 94     ‘‘‘
 95     return "-".join("%s" %i for i in getyearandmonth(n))
 96
 97 def getyearandmonth(n=0):
 98     ‘‘‘‘‘
 99     get the year,month,days from today
100     befor or after n months
101     ‘‘‘
102     thisyear = int(year)
103     thismon = int(mon)
104     totalmon = thismon+n
105     if(n>=0):
106         if(totalmon<=12):
107             days = str(get_days_of_month(thisyear,totalmon))
108             totalmon = addzero(totalmon)
109             return (year,totalmon,days)
110         else:
111             i = totalmon/12
112             j = totalmon%12
113             if(j==0):
114                 i-=1
115                 j=12
116             thisyear += i
117             days = str(get_days_of_month(thisyear,j))
118             j = addzero(j)
119             return (str(thisyear),str(j),days)
120     else:
121         if((totalmon>0) and (totalmon<12)):
122             days = str(get_days_of_month(thisyear,totalmon))
123             totalmon = addzero(totalmon)
124             return (year,totalmon,days)
125         else:
126             i = totalmon/12
127             j = totalmon%12
128             if(j==0):
129                 i-=1
130                 j=12
131             thisyear +=i
132             days = str(get_days_of_month(thisyear,j))
133             j = addzero(j)
134             return (str(thisyear),str(j),days)
135
136 def addzero(n):
137     ‘‘‘‘‘
138     add 0 before 0-9
139     return 01-09
140     ‘‘‘
141     nabs = abs(int(n))
142     if(nabs<10):
143         return "0"+str(nabs)
144     else:
145         return nabs
146
147 def get_today_month(n=0):
148     ‘‘‘‘‘
149     获取当前日期前后N月的日期
150     if n>0, 获取当前日期前N月的日期
151     if n<0, 获取当前日期后N月的日期
152     date format = "YYYY-MM-DD"
153     ‘‘‘
154     (y,m,d) = getyearandmonth(n)
155     arr=(y,m,d)
156     if(int(day)<int(d)):
157         arr = (y,m,day)
158     return "-".join("%s" %i for i in arr)
159
160
161 if __name__=="__main__":
162     print today()
163     print todaystr()
164     print datetime()
165     print datetimestr()
166     print get_day_of_day(20)
167     print get_day_of_day(-3)
168     print get_today_month(-3)
169     print get_today_month(3)
时间: 2024-08-08 23:13:47

【python】python获取当前日期前后N天或N月的日期的相关文章

python获取当前日期前后N天或N月的日期

# -*- 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",l

Python中获取当前日期的格式

在Python里如何获取当前的日期和时间呢?在Python语言里,我们可以通过调用什么模块或者类函数来得到当前的时间或日期呢? 当然你可以使用时间模块(time module),该模块提供了各种和时间相关的函数.但是这个模块里的一些函数在某些平台里不可用.那么怎么办呢?我们 可以使用一个更高级的面向对象的接口函数:datetime.它提供了操作日期和时间的多种简单或复杂的方法. python里使用time模块来获取当前的时间 1 2 3 time.strftime(format) time.st

js获取当前日期、前一天、后一天的日期的例子

<script> function addByTransDate(dateParameter, num) { var translateDate = "", dateString = "", monthString = "", dayString = ""; translateDate = dateParameter.replace("-", "/").replace(&qu

python脚本获取时间格式

来源 Python中获取当前日期的格式:https://www.cnblogs.com/wenBlog/p/6023742.html #!/usr/bin/python # -*- coding: utf-8 -*- import time print (time.strftime("%H:%M:%S")) ## 12 hour format ## print (time.strftime("%I:%M:%S")) import time print (time.s

python 获取当前日期 星期

from datetime import datetime d =datetime.today()     #获取当前日期时间 d.isoweekday()           #获取时间周几 python 获取当前日期 星期,布布扣,bubuko.com

Python脚本获取参数的方式

在运维过程中,常常需要自己写脚本,而python往往是最佳的选择.那么怎么获取python脚本的命令行参数呢,例如: python demo.py a b c 怎么获取命令行参数,a,b,c 呢?可以通过sys库里面的argv来实现, 例如: $ cat demo.py #-*- coding: UTF-8 -*- import os import sys def demo(): print sys.argv print len(sys.argv) for i in range(len(sys.

Python下获取当前目录中的所有子目录

p是输入目录 代码如下 import osdef getDirList(p):  #      b = [];    filepath=p    if filepath=="":        return b    filepath = filepath.replace( "/","\\")    if filepath[ -1] != "\\":        filepath = filepath+"\\&qu

【python】获取51cto博客的文章列表

python的正则与网页操作练习二: import re import urllib.request #51cto urlcode=gb18030 class down51web: s_url='' s_blogid='' s_blogpages='' s_html='' s_code='' def __init__(self,url,code): self.s_url=url self.s_code=code def get_html(self): self.s_html=urllib.req

Python中获取异常(Exception)信息

异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置.下面介绍几种python中获取异常信息的方法,这里获取异常(Exception)信息采用try...except...程序结构.如下所示 try: ... except Exception as e: ... 1.str(e) 返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信息 'integer division or modulo by zero' 2.repr(e) 给出较全的异常信息,包括异