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. python——selenium库的使用

    selenium 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Fire ...

  2. 项目Alpha冲刺(团队)-测试篇

    格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(团队)-代码规范.冲刺任务与计划 团队名称:为了交项目干杯 测试用例:测试用例文档.zip 作业目标:描述项目的测试 ...

  3. danci3

    permit 英 [pə'mɪt] 美 [pɚ'mɪt] vi. 许可:允许 vt. 许可:允许 n. 许可证,执照 encapsulate 英 [ɪn'kæpsjʊleɪt; en-] 美 [ɪn' ...

  4. (转)python自动化测试之异常及日志

    为了保持自动化测试用例的健壮性,异常的捕获及处理,日志的记录对掌握自动化测试执行情况尤为重要,这里便详细的介绍下在自动化测试中使用到的异常及日志,并介绍其详细的用法. 一.日志 打印日志是很多程序的重 ...

  5. pandas 6 时间

    类 备注 创建方法 Timestamp 时刻数据 to_datetime,Timestamp DatetimeIndex Timestamp的索引 to_datetime,date_range,Dat ...

  6. python列表相关函数

    1.python中可用于列表的函数 (1)cmp(list1, list2) 比较两个列表的元素 (2)len(list) 列表元素个数 (3)max(list) 返回列表元素最大值 (4)min(l ...

  7. 关于new FormData() 对象的用法

    formData.append()  理论上本身若键值已经存在,那么我们append的数据是进行类似push的操作,为了匹配php,我们进行加了[]  ,这个操作.!

  8. 查看.NET应用程序中的异常(上)

    内存转储是查明托管.NET应用程序中异常的原因的一种极好的方法,特别是在生产应用程序中发生异常时.当您在无法使用Visual Studio的应用程序中跟踪异常时,cdb和sos.dll的使用技术就变成 ...

  9. Windbg的命令

    前面介绍了Windbg的UI功能,也基本上能完成基本的调试任务,但是WinDBG主要是以命令方式工作的,这些命令在Command Window里输入.WinDBG共支持三类命令:标准命令.元命令和扩展 ...

  10. 转载:scala中的:+\+:\::\:::

    原文链接:https://segmentfault.com/a/1190000005083578 初学Scala的人都会被Seq的各种操作符所confuse.下面简单列举一下各个Seq操作符的区别. ...