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

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

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

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

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

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

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

# -*- 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 = ""
if (int(mon) < 10):
mon = "" + 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 = ""
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 "" + 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()#
print datetime()#2017-12-02 16:37:19
print datetimestr()#
print get_day_of_day(20)#获取20天后的日期,2017-12-22
print get_day_of_day(-3)#获取3天前的日期,2017-11-29
print get_today_month(-3)#获取3个月前的日期, 2017-09-02
print get_today_month(3)# 获取3个月后的日期, 2018-03-02
print get_today_month(19)# 获取19个月后的日期,2019-07-02

python:日期计算的更多相关文章

  1. python 日期计算案例

    一.计算两个日期内的所有月 def get_month_interval(start_str, end_str): start_year, start_month = list(map(int, st ...

  2. Python日期计算

    Python源代码如下: # -*- coding: UTF-8 -*- """ 简述:要求输入某年某月某日 提问:求判断输入日期是当年中的第几天? Python解题思路 ...

  3. python 日期计算

    from datetime import timedelta,datetime import time tdy = datetime.today() tdy = tdy.strftime(" ...

  4. 【转载】Python日期时间模块datetime详解与Python 日期时间的比较,计算实例代码

    本文转载自脚本之家,源网址为:https://www.jb51.net/article/147429.htm 一.Python中日期时间模块datetime介绍 (一).datetime模块中包含如下 ...

  5. python 日期相关的各种操作总结

    用 Python 做项目时,经常会遇到与日期转换相关,日期计算相关的功能,动不动就要去查python手册,感觉麻烦,因此把自己常用的一些东西,总结了一下,总体说来到目前为止遇到如下一些需求: 1. 用 ...

  6. Python日期时间函数处理

    所有日期.时间的 api 都在datetime模块内. 1 日期的格式化输出 datetime => string import datetime now = datetime.datetime ...

  7. Python 日期和时间(转)

    Python 日期和时间 Python程序能用很多方式处理日期和时间.转换日期格式是一个常见的例行琐事.Python有一个 time 和 calendar 模组可以帮忙. 什么是Tick? 时间间隔是 ...

  8. (转)Python 日期和时间

    转自http://www.runoob.com/python/python-date-time.html Python 日期和时间 Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见 ...

  9. Python 日期时间处理模块学习笔记

    来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...

  10. 【310】◀▶ Python 日期和时间

    参考: python 时间日期计算 Python 日期和时间(菜鸟教程) 8.1. datetime — Basic date and time types python中datetime模块中dat ...

随机推荐

  1. SpringBoot使用thymeleaf案例

    1 编写application.properties文件 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=. ...

  2. 极限挑战----3小时完成OA系统(失败)

    今天老师要求三小时把OA系统做出了,之前一点也没接触过,对其不了解,而且这几天一直把时间放在六级了,对Web重视有点少. 最终我只做了登录和校验,可以显示富文本框,但不能提交数据库. 总之还有还多没有 ...

  3. WinDbg常用命令系列---||(系统状态)

    ||(系统状态) 简介 双竖线 ( || ) 命令将打印指定的系统或当前正在调试的所有系统的状态. 使用形式 || System 参数 System 指定要显示的系统. 如果省略此参数,将显示正在调试 ...

  4. 「ZJOI2019」麻将

    传送门 Solution  对于条件一:记录一个\(cnt\)表示牌个数\(≥2\)的个数 设\(dp_{i,0/1,j,k}\)表示考虑了\(1...i\),当前是否有对子,以\(i-1\),\(i ...

  5. fluent运行过程中转换边界

    我们以一个简单的VOF算例来说明,算例模型如下: 算例中空气为主相,水为次相.开始时刻,inlet_one设置为速度入口边界,速度为1m/s,且水的体积分数为100%,inlet_two设置为速度入口 ...

  6. 【解决方案】Chrome崩溃问题解决

    问题描述 出现异常之前做的操作就是,因为换工位的需要,所以关闭电脑,修改网络配置. 问题分析 Firefox和其他应用网络正常 Chrome设置.帮助等选项均打不开 分析,很可能是电脑重启后,Wind ...

  7. FusionInsight,一个融合的大数据平台

    随着物联网技术和应用的普及,以运营商.互联网以及实体经济行业为代表的企业产生了越来越多的数据,大数据的发展越来越蓬勃. 从2007年开始,大数据应用成为很多企业的需求,2012年兴起并产生了大数据平台 ...

  8. hadoop 综合大作业

    作业要求来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3339 本次作业是在期中大作业的基础上利用hadoop和hive技术进行 ...

  9. 第07组 Alpha事后诸葛亮

    1.请在博客开头给出组长博客链接(3.1 2分) 团队:摇光 队长:杨明哲 组长博客:这里 2.参考邹欣老师的问题模板进行总结思考(3.2 27分) 设想和目标(2分) 1.我们的软件要解决什么问题? ...

  10. hdu5387 钟表指针之间夹角(分数计算,模拟)

    题意: 给你一个24格式的数字时间,(字符串),问你这个时刻时针与分针 时针与秒针 分针与秒针 之间的夹角, 我们发现 秒针每秒转6度,分针每秒转1/10度,每分转6度,时针每小时转30度,每分转1/ ...