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. P2606 [ZJOI2010]排列计数

    P2606 [ZJOI2010]排列计数 因为每个结点至多有一个前驱,所以我们可以发现这是一个二叉树.现在我们要求的就是以1为根的二叉树中,有多少种情况,满足小根堆的性质. 设\(f(i)\)表示以\ ...

  2. win10下无法安装loadrunner,提示“管理员已阻止你运行此应用”

    如下图: 1.再次进入控制面板,并且选择用户账户后把最下面的[更改用户账户控制设置],里面有个滑条,把滑条拉到最下面的[从不通知]上面并且确定. 2.按[Win+R]快捷键打开运行,输入 gpedit ...

  3. Nginx+keepalived 高可用双机热备(主从模式)

    环境:centos7.6 最小化安装 主:10.11.1.32 从:10.11.1.33 VIP:10.11.1.130 修改主节点主机名: hostnamectl set-hostname web_ ...

  4. Laravel —— batch 实现

    很多项目中会用到自动执行脚本的功能, 例如,自动统计上个月的注册用户,定时生成 csv 文件并邮箱发送给客户等等. Laravel 中的任务调度,可实现定时任务, 结合自定义 artisan 命令,即 ...

  5. 35 Top Open Source Companies

    https://www.datamation.com/open-source/35-top-open-source-companies-1.html If you think of open sour ...

  6. LeetCode 723. Candy Crush

    原题链接在这里:https://leetcode.com/problems/candy-crush/ 题目: This question is about implementing a basic e ...

  7. shell脚本 基础应用

    变量分为普通变量可只读变量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 ...

  8. Python 企业面试题集锦之Python基础

    △字符串.列表.元组.字典每个常用的5个方法? 字符串: 字符串用单引号(')或双引号(")括起来,不可变. s.strip(c):去除空格或指定的字符c:lstrip/rstrip: s. ...

  9. 【2019.11.18】SDN阅读作业

    为什么需要SDN?SDN特点? 随着网络的快速发展,传统互联网出现了如传统网络配置复杂度高等诸多问题,这些问题说明网络架构需要革新,可编程网络的相关研究为 SDN 的产生提供了可参考的理论依据 SDN ...

  10. 循环(for,while,until)与循环控制符(break,continue)

    一.for循环 第一种风格   for ((;;;))(类似C语言风格) do command done 例子:for ((i=0;i<10;i++)) do echo $i done 第二种风 ...