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. JQuery系列(3) - 工具方法

    jQuery函数库提供了一个jQuery对象(简写为$),这个对象本身是一个构造函数,可以用来生成jQuery对象的实例.有了实例以后,就可以调用许多针对实例的方法,它们定义jQuery.protot ...

  2. NPM——npm|cnpm如何升级

    前言 手动更新了node.js版本后,想要升级下npm的版本 步骤 其实无论npm还是cnpm升级的命令都是一样的,除了需要指定包名. 升级npm $ npm install -g npm 查看npm ...

  3. SparkSQL读写外部数据源-json文件的读写

    object JsonFileTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .m ...

  4. JS优化常用片断

    防抖debounce装饰器 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时. function debounce(func, delay) { let isCooldown = fa ...

  5. Java中多态

    多态:把子类看成是父类,把实现类看成是接口,这样类就具有多种形态,称为多态. 在多态中访问成员变量,访问的是父类中的成员变量. 在多态中访问成员方法,先访问的是子类,看看子类有没有覆盖重写要访问的父类 ...

  6. WinDbg常用命令系列---内存数据显示和对应符号显示d*s(dds、dps、dqs)

    命令dds, dps,  dqs显示给定范围内的内存内容.假定该内存是符号表中的一系列地址.相应的符号也会显示出来. dds [Options] [Range] dqs [Options] [Rang ...

  7. ping fping

    通过ping来监测对端网络状态 ping fpinf在windows和linux上的参数是不同的,返回的结果也是不同的 在网络连通性监测方面用的比较多,在py go中调用命令,对返回的结果使用正则来在 ...

  8. java web项目改装exe安装版

    https://blog.csdn.net/rico_zhou/article/details/79868129java简单程序打包成exe https://blog.csdn.net/rico_zh ...

  9. 移动端ios针对input虚拟键盘挡住的问题

    写移动端的时候发现input的虚拟键盘对Ios的手机不是很友好 我的是苹果6 点击的时候经常会挡住input框 针对这个问题找了很多发现都没效果 最后发现用下面这段js就可以解决了 $("i ...

  10. Configure JSON.NET to ignore DataContract/DataMember attributes

    https://stackoverflow.com/questions/11055225/configure-json-net-to-ignore-datacontract-datamember-at ...