相关文章推荐
忐忑的铁板烧  ·  上海到广州火车票查询-火车票车次查询购买[携 ...·  2 月前    · 
面冷心慈的汉堡包  ·  方崔激辩转基因落选 ...·  1 年前    · 
慷慨的烈马  ·  大熊猫国家公园川陕甘毗邻地区联合执法整治专项 ...·  1 年前    · 
坐怀不乱的猕猴桃  ·  《鬼船玛丽号》影评:幽灵船的恐怖与迷人之处·  2 年前    · 
神勇威武的红豆  ·  在海上漂流15年的2万多只小黄鸭,能给我们带 ...·  2 年前    · 
Code  ›  python获取日期加减之后的日期开发者社区
python date days strftime
https://cloud.tencent.com/developer/article/1406636
善良的回锅肉
2 年前
作者头像
周小董
0 篇文章

python获取日期加减之后的日期

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > python前行者 > python获取日期加减之后的日期

python获取日期加减之后的日期

作者头像
周小董
发布 于 2019-03-25 17:12:56
3.9K 0
发布 于 2019-03-25 17:12:56
举报

python语言中的datetime模块可以利用其中的方法获取不同的日期,比如获取当前日期、明天、昨天、上个月、下个月和明年。下面利用几个实例说明这些日期的获取方法,操作如下:

image.png

第一步,利用datetime模块获取当前日期 datetime.date.today(); 如下图所示:

image.png

第二步,获取当前日期前一天日期,利用当前日期减去一天,如下图所示:

image.png

第三步,获取当前日期后一天日期,利用当前日期加上一天,如下图所示:

image.png

第四步,获取当前日期下一个月日期,利用当前日期加上30天,如下图所示:

image.png

第五步,获取当前日期上一个月的日期,利用当前日期减去30天,如下图所示:

image.png

第六步,获取当前日期返回明年今天的日期,利用当前日期加上365天,如下图所示:

image.png
  • python获取前后N天或前后N个月的日期
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------------
import datetime
#获取366天前的日期
day=(datetime.date.today() - datetime.timedelta(days=366)).strftime('%Y-%m-%d')
print(day)
#获取366天后的日期
day=(datetime.date.today() + datetime.timedelta(days=366)).strftime('%Y-%m-%d')
print(day)
#3周前期
day=(datetime.date.today() + datetime.timedelta(weeks=-3)).strftime('%Y-%m-%d')
print(day)
#-----------------------------------------------------------------------------------
'''获取当前日期前后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()#获取当前日期,2017-12-02
    print todaystr()#20171202
    print datetime()#2017-12-02 16:37:19
 
推荐文章
忐忑的铁板烧  ·  上海到广州火车票查询-火车票车次查询购买[携程手机版火车票预订]
2 月前
面冷心慈的汉堡包  ·  方崔激辩转基因落选 科普化解PX危机入选_中国经济网��国家经济门户
1 年前
慷慨的烈马  ·  大熊猫国家公园川陕甘毗邻地区联合执法整治专项行动拉开帷幕-广元市人民政府手机版
1 年前
坐怀不乱的猕猴桃  ·  《鬼船玛丽号》影评:幽灵船的恐怖与迷人之处
2 年前
神勇威武的红豆  ·  在海上漂流15年的2万多只小黄鸭,能给我们带来什么海洋知识?_鸭子
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号