转载至https://blog.csdn.net/p9bl5bxp/article/details/54945920

Python中提供了多个用于对日期和时间进行操作的内置模块:time模块、datetime模块和calendar模块。其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h基本一致。time模块相比,datetime模块提供的接口更直观、易用,功能也更加强大,calendar在处理年历和月历上功能强大。

相关术语的解释

UTC time,世界协调时间,又称格林尼治天文时间、世界标准时间。与UTC time对应的是各个时区的local time,东N区的时间比UTC早N个小时,用UTC+N表示,西N区的时间比UTC晚N个小时,用UTC-N表示。

epoch time,表示时间开始的起点,是一个特定时间,不同平台上这个时间点额定值不太相同,如unix上为1970-01-01 00:00:00 UTC。

时间戳,也称为unix时间或POSIX时间,它是一种时间表示方式,表示从格林尼治时间1970年1月1日0时0分0秒开始到现在所经过的毫秒数,其值为float类型。 但是有些编程语言的相关方法返回的是秒数(Python就是这样),这个需要看方法的文档说明。需要说明的是时间戳是个差值,其值与时区无关。

一、time模块

三种表现形式

二、datetime模块

datetime模块定义了以下几类:

类名称 描述
datetime.date 表示日期,常用的属性有:year,month和day
datetime.time 表示时间,常用属性有:hour,minute,second,microsecond
datetime.datetime 表示日期时间
datetime.timedelta 表示两个date、time、datetime实例之间的时间间隔
datetime.tzinfo 时区相关信息对象的抽象基类,它们由datetime和time类使用,以提供自定义时间的而调整。
datetime.timezone 实现tzinfo抽象基类的类,表示与UTC固定的偏移量

1.date类

from datetime import date
# 1.date(year,month,day) 返回datetime时间
date(2012,11,9)
>>> 2012-12-12
# 2.date.today() 返回当天日期
>>> 2020-05-05
# 3.date.fromtimestamp(timestamp) 根据跟定的时间戳,返回一个date对象
date.fromtimestamp(time.time())
>>> 2020-05-05
# 4.对象方法和属性
对象方法/属性名称 描述
d.year
d.month
d.day
d.replace(year[, month[, day]]) 生成并返回一个新的日期对象,原日期对象不变
d.timetuple() 返回日期对应的time.struct_time对象
d.toordinal() 返回日期是是自 0001-01-01 开始的第多少天
d.weekday() 返回日期是星期几,[0, 6],0表示星期一
d.isoweekday() 返回日期是星期几,[1, 7], 1表示星期一
d.isocalendar() 返回一个元组,格式为:(year, weekday, isoweekday)
d.isoformat() 返回‘YYYY-MM-DD’格式的日期字符串
d.strftime(format) 返回指定格式的日期字符串,与time模块的strftime(format, struct_time)功能相同

2.time类

class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]])

类方法/属性名称 描述
time.max time类所能表示的最大时间:time(23, 59, 59, 999999)
time.min time类所能表示的最小时间:time(0, 0, 0, 0)
time.resolution 时间的最小单位,即两个不同时间的最小差值:1微秒
对象方法/属性名称 描述
t.hour
t.minute
t.second
t.microsecond 微秒
t.tzinfo 返回传递给time构造方法的tzinfo对象,如果该参数未给出,则返回None
t.replace(hour[, minute[, second[, microsecond[, tzinfo]]]]) 生成并返回一个新的时间对象,原时间对象不变
t.isoformat() 返回一个‘HH:MM:SS.%f’格式的时间字符串
t.strftime() 返回指定格式的时间字符串,与time模块的strftime(format, struct_time)功能相同

3.datetime类

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

类方法/属性名称 描述
datetime.today() 返回一个表示当前本期日期时间的datetime对象
datetime.now([tz]) 返回指定时区日期时间的datetime对象,如果不指定tz参数则结果同上
datetime.utcnow() 返回当前utc日期时间的datetime对象
datetime.fromtimestamp(timestamp[, tz]) 根据指定的时间戳创建一个datetime对象
datetime.utcfromtimestamp(timestamp) 根据指定的时间戳创建一个datetime对象
datetime.combine(date, time) 把指定的date和time对象整合成一个datetime对象
datetime.strptime(date_str, format) 将时间字符串转换为datetime对象
对象方法/属性名称 描述
dt.year, dt.month, dt.day 年、月、日
dt.hour, dt.minute, dt.second 时、分、秒
dt.microsecond, dt.tzinfo 微秒、时区信息
dt.date() 获取datetime对象对应的date对象
dt.time() 获取datetime对象对应的time对象, tzinfo 为None
dt.timetz() 获取datetime对象对应的time对象,tzinfo与datetime对象的tzinfo相同
dt.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) 生成并返回一个新的datetime对象,如果所有参数都没有指定,则返回一个与原datetime对象相同的对象
dt.timetuple() 返回datetime对象对应的tuple(不包括tzinfo)
dt.utctimetuple() 返回datetime对象对应的utc时间的tuple(不包括tzinfo)
dt.toordinal() 同date对象
dt.weekday() 同date对象
dt.isocalendar() 同date独享
dt.isoformat([sep]) 返回一个‘%Y-%m-%d
dt.ctime() 等价于time模块的time.ctime(time.mktime(d.timetuple()))
dt.strftime(format) 返回指定格式的时间字符串
from datetime import datetime, timedelta, timezone, tzinfo
1.获取指定日期和时间
>>> d = datetime(2012,11,12,14,45,45)
>>> print(d)
>>> 2012-11-12 14:45:45
2.datetime转换为timestamp
>>> d = d.timestamp()
>>> 1352702745.0
3.timestamp转换为datetime
>>> t = 1352702745.0
>>> t.fromtimestamp()
>>> 2012-11-12 14:45:45
4.str转换为datetime
>>> c = datetime.strptime("2012-11-12 14:45:45","%Y %m %d %H:%M:%S")
>>> print(c)
>>> 2012-11-12 14:45:45
5.datetime转化为str
>>> datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S")
>>> 2020-05-05 17:20:13
6.datetime加减
timedelta(days,hours,...)
>>> now = datetime.now()
>>> now + timedelta(hours=1)
>>> 2020-05-05 18:23:42.756201
7.时区转换
>>> d = datetime.utcnow() #获取utc时间
>>> d = d.replace(tzinfo=timezone.utc) #强制设置时区为UTC+0:00
>>> print(d)
>>> 2020-05-05 09:27:07.131068+00:00
>>> d = d.astimezone(tzinfo=timezone(timedelta(hours=8))) #astimezone()将转换时区为北京时间
>>> print(d)
>>> 2020-05-05 17:29:18.927426+08:00

三、calendar模块

import calendar
# 1.calendar.isleap(year),判断year是否为闰年
calendar.isleap(2018)
>>> False
# 2.calendar.leapdays(y1,y2),返回在y1,y2两年之间的闰年总数,不包含y2。
calendar.leapdays(2012,2020)
>>> 2
# 3.calendar.month(year,month),返回year的month日历
calendar.month(2018, 12)
>>> December 2018
Mo Tu We Th Fr Sa Su
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
# 4.calendar.monthrange(year,month),返回某月的第一天是星期几和这个月的天数,第一个是该月第一天是星期几(返回数+1),第二个是该月有多少天。
calendar.monthrange(2020,5)
>>> (4, 31)
# 5.calendar.monthcalendar(year,month),返回某月每一周的列表集合
calendar.monthcalendar(2020,5)
>>>[[0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
# 6.calendar.setfirstweekday(weekday),设置每周以周几开始算
celendar.setfirstweekday(3)
# 7.calendar.weekday(year,month,day) #返回给定日期是周几
calendar.weekday(2020,5,5)
>>> 1
# 8.calendar.timegm(tupletime) #接受一个时间元祖,返回该时刻的时间戳
calendar.timegm(time.localtime())
>>> 1588693967

【Python】【第二节】【时间与日期处理模块】的更多相关文章

  1. Python中的时间与日期

    本文简要介绍datetime,time模块的简要用法. datetime模块 datetime模块主要有四个主要的对象. date 处理年.月.日 time处理时.分.秒.微秒 datetime处理日 ...

  2. python 第二节课内容和练习

    一.列表 []表示列表,用','进行分隔,list有序 能够进行索引 切片 (in append extend count index insert pop remove,reverse sort c ...

  3. Python 关于时间和日期函数使用 -- (转)

    python中关于时间和日期函数有time和datatime   1.获取当前时间的两种方法: import datetime,time now = time.strftime("%Y-%m ...

  4. Python标准库:datetime 时间和日期模块 —— 时间的获取和操作详解

    datetime 时间和日期模块 datetime 模块提供了以简单和复杂的方式操作日期和时间的类.虽然支持日期和时间算法,但实现的重点是有效的成员提取以进行输出格式化和操作.该模块还支持可感知时区的 ...

  5. Python中的时间模块和日期模块

    Python 日期和时间 Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能. Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间. 时间间 ...

  6. Python中的时间日期模块(time、datetime)

    目录 Datetime 获取当前时间 获取当前日期 获取当前时间的tuple元组 格式化日期和时间 时间移动 获取两个时间的时间差 时间格式转换 Time 获取距元年(1970.1.1)的秒数 当时时 ...

  7. Python 时间和日期模块的常用例子

    获取当前时间的两种方法 import datetime,time now = time.strftime("%Y-%m-%d %H:%M:%S") print now now = ...

  8. Python学习(12)日期和时间

    目录 Python 日期和时间 时间元组 获取当前时间 获取格式化时间 格式化日历 获取某月日历 Time模块 日历模块 其他相关模块和函数 Python 日期和时间 Python 程序能用很多方式处 ...

  9. 孤荷凌寒自学python第二十九天python的datetime.time模块

     孤荷凌寒自学python第二十九天python的datetime.time模块 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) datetime.time模块是专门用来表示纯时间部分的类. ...

随机推荐

  1. HTTPS之密钥知识与密钥工具Keytool和Keystore-Explorer

    1 简介 之前文章<Springboot整合https原来这么简单>讲解过一些基础的密码学知识和Springboot整合HTTPS.本文将更深入讲解密钥知识和密钥工具. 2 密钥知识-非对 ...

  2. 报错:require_once cannot allocate memory----php,以前自己弄的稍微有点特殊的开发环境

    最近出现过一个问题,值得记录 类似于这样的报错的问题: Warning: require_once(/www/app/somecomponent.php): failed to open stream ...

  3. python 字符与数字如何转换

    python中字符与数字相互转换用chr()即可. python中的字符数字之间的转换函数 int(x [,base ])                               将x转换为一个整 ...

  4. (四)PL/SQL运算符

    运算符是一个符号,告诉编译器执行特定的数学或逻辑操作. PL/SQL语言有丰富的内置运算符,运算符提供的以下几种类型: 1.算术运算符 2.关系运算符 3.比较运算符 4.逻辑运算符 5.字符串运算符 ...

  5. (转)如何学好C语言

    原文:http://coolshell.cn/articles/4102.html    作者:陈皓 有人在酷壳的留言版上询问下面的问题 keep_walker : 今天晚上我看到这篇文章. http ...

  6. (转)mysql数据库表名批量修改大小写

    由于不用服务器对mysql的表名的大小写敏感要求不一致,经常在出现线上的数据库down到了本地不能运行的情况,贴出一段代码用来批量修改数据库表名大小写. DELIMITER // DROP PROCE ...

  7. 爱创课堂每日一题第五十四天- 列举IE 与其他浏览器不一样的特性?

    IE支持currentStyle,FIrefox使用getComputStyle IE 使用innerText,Firefox使用textContent 滤镜方面:IE:filter:alpha(op ...

  8. Node Mysql事务处理封装

    node回调函数的方式使得数据库事务貌似并没有像java.php那样编写简单,网上找了一些事务处理的封装并没有达到自己预期的那样简单编写,还是自己封装一个吧.封装的大体思路很简单:函数接受一个事务处理 ...

  9. pomelo安装笔记

    npm install -dnpm config set registry https://registry.npm.taobao.orgnpm install pomelo -gpomelo lis ...

  10. 图论--差分约束--HDU\HDOJ 4109 Instrction Arrangement

    Problem Description Ali has taken the Computer Organization and Architecture course this term. He le ...