Python时间与日期操作(datetime、time、calendar)
来源:互联网 发布:cmd连不上mysql 编辑:程序博客网 时间:2024/05/29 20:00
名词解释
UTC(CoordinatedUniversal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。
DST(DaylightSaving Time)即夏令时。是一种为节约能源而人为规定地方时间的制度,一般在天亮早的夏季人为将时间提前一小时。
相关模块
模块
说明
time
time是一个仅包含与日期和时间相关的函数和常量的模块,在本模块中定义了C/C++编写的几个类。例如,struct_time类。
datetime
datetime是一个使用面向对象编程设计的模块,可以在Python中使用日期和时间。它定义了几个表示日期和时间的类。
calendar
日历是一个提供函数的模块,以及与Calendar相关的几个类,它们支持将日历映像生成为text,html,….
locale
该模块包含用于格式化或基于区域设置分析日期和时间的函数。
时间元组
许多Python时间函数将时间处理为9个数字的元组,如下所示:
索引
字段
值
0
4位数,表示年份
2018,2019…
1
月份
1 ~ 12
2
日期
1 ~ 31
3
小时
0 ~ 23
4
分钟
0 ~ 59
5
秒
0 ~ 61(60或61是闰秒)
6
星期几
0 ~ 6(0是星期一)
7
一年的第几天
1 ~ 366(朱利安日)
8
夏令时
-1,0,1,-1是决定是否为夏令时的旗帜
代码表示:
year (four digits, e.g. 1998)month (1-12)day (1-31)hours (0-23)minutes (0-59)seconds (0-59)weekday (0-6, Monday is 0)Julian day (day in the year, 1-366)#夏令时格式,0:正常格式,1:夏令时格式,-1:根据当前的日期时间格式来判定DST (Daylight Savings Time) flag (-1, 0 or 1)
上面的元组相当于struct_time结构。此结构具有以下属性:
索引
字段
值
0
tm_year
2018,2019…
1
tm_mon
1 ~ 12
2
tm_mday
1 ~ 31
3
tm_hour
0 ~ 23
4
tm_min
0 ~ 59
5
tm_sec
0 ~ 61(60或61是闰秒)
6
tm_wday
0 ~ 6(0是星期一)
7
tm_yday
1 ~ 366(朱利安日)
8
tm_isdst
-1,0,1,-1是决定是否为夏令时的旗帜
可用如下图示表示:
time模块
time
模块,它提供了处理时间和表示之间转换的功能。help(time)之后可以知道time有2种时间表示形式:
1、时间戳表示法,即以整型或浮点型表示的是一个以秒为单位的时间间隔。这个时间的基础值是从1970年的1月1号零点开始算起。
2、元组格式表示法,这个元组有9个整型内容。分别表示不同的时间含义。
time模块的常用函数
编号
方法
描述
1
time.time()
返回当前时间时刻,浮点数形式秒数,不支持参数。
2
time.clock()
返回当前程序的cpu执行时间。为了测量不同方法的计算成本,time.clock的值比time.time()的值更有用。unix系统始终返回全部运行时间;而windows从第二次开始都是以第一次调用此函数时的时间戳作为基准。
3
time.sleep(secs)
暂停调用线程secs秒,接受整型和浮点型参数。
4
time.gmtime
([secs])
将时间戳转换为UTC时间元组格式。接受一个浮点型时间戳参数,其默认值为当前时间戳。
5
time.localtime
([secs])
将时间戳转换为本地时间元组格式。接受一个浮点型时间戳参数,其默认值为当前时间戳。
6
time.asctime
([tupletime])
接受时间元组,并返回一个可读的24个字符的字符串,例如’Tue Dec 11 22:07:14 2019’,默认值为localtime()返回值。
7
time.ctime
([secs])
接受时间戳,转换为字符串。其默认值为当前时间戳。函数等价于asctime(localtime(seconds))。
8
time.mktime
(tupletime)
将本地时间元组,转换为时间戳(浮点值,该时间点以秒为单位表示。)。接受一个时间元组,必选。
9
time.strftime
(fmt[,tupletime])
将时间元组以指定的格式(字符串fmt指定)转换为字符串形式。接受字符串格式化串、时间元组。时间元组为可选,默认为localtime()
10
time.strptime
(str,fmt=“”)
根据格式字符串fmt解析str,并返回元组格式的时间。
strftime()的逆向过程。接受字符串,时间格式2个参数,都是必选。
11
time.altzone
本地DST时区的偏移量(以秒为单位的UTC)。
12
time.tzset()
改变本地时区
时间字符串支持的格式符号:
格式 含义 备注%a 本地(locale)简化星期名称%A 本地完整星期名称%b 本地简化月份名称%B 本地完整月份名称%c 本地相应的日期和时间表示%d 一个月中的第几天(01 - 31)%H 一天中的第几个小时(24小时制,00 - 23)%I 第几个小时(12小时制,01 - 12)%j 一年中的第几天(001 - 366)%m 月份(01 - 12)%M 分钟数(00 - 59)%p 本地am或者pm的相应符%S 秒(01 - 61)%U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。%w 一个星期中的第几天(0 - 6,0是星期天)%W 和%U基本相同,不同的是%W以星期一为一个星期的开始。%x 本地相应日期%X 本地相应时间%y 去掉世纪的年份(00 – 99)%Y 完整的年份%Z 时区的名字(如果不存在为空字符)%% ‘%’字符
注意:
1、“%p”只有与“%I”配合使用才有效果。
2、文档中强调确实是0-61,而不是59,闰年秒占两秒
3、当使用strptime()函数时,只有当在这年中的周数和天数被确定的时候%和%W才会被计算。
time模块重要属性
编号
属性
描述
1
time.timezone
UTC和本地时区(不含DST)之间的偏移量,以秒计。
2
time.tzname
关于(标准时区名称, 夏令时时区名称)的元组
3
time.altzone
当地夏令时时间与标准UTC时间的误差,以秒计
4
time.daylight
当地时间是否反映夏令时,默认为0
time模块示例
# coding=utf-8'''Created on 2017年8月27日 @author: zxt'''importtime # Secondsticks = time.time() # 这个形式不能表示在时代(1970年1月1日上午12:00)之前的日期。# 而且截止点为3038年的某个时刻,在未来的日子也不能以这种方式表示print("Number of ticks since 12:00am, January 1, 1970:", ticks); # 获取当前本地时间localtime =time.localtime(time.time());print("Local current time :", localtime);# 当前时间curtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());print(curtime);# 也可以使用asctime()进行时间格式化print(time.asctime(localtime));
Calendar
模块
calendar模块提供与日历相关的功能,包括为给定的月份或年份打印文本日历的功能。
默认情况下,日历将星期一作为一周的第一天,将星期日作为最后一天。如果想要更改这个,可调用calendar.setfirstweekday()函数设置修改。
以下是calendar模块可用的功能函数列表
函数
描述
Calendar
(year,w = 2,l = 1,c = 6)
返回一个具有年份日历的多行字符串格式化为三列,以c
个空格分隔。 w
是每个日期的字符宽度;每行的长度为21 * w + 18 + 2 * c
,l
是每周的行数。
firstweekday( )
返回当前设置每周开始的星期。默认情况下,当日历首次导入时设置为:0
,表示为星期一。
isleap(year)
如果给定年份(year
)是闰年则返回True
;否则返回:False
。
leapdays(y1,y2)
返回在范围(y1
,
y2)
内的年份中的闰年总数。
Month
(year,month,w = 2,l = 1)
返回一个多行字符串,其中包含年份月份的日历,每周一行和两个标题行。 w
是每个日期的字符宽度;每行的长度为7 * w + 6
。 l
是每周的行数。
Monthcalendar(year,month)
返回int
类型的列表。每个子列表表示一个星期。年份月份以外的天数设置为0
;该月内的日期设定为月份的第几日:1 ~ 31。
Monthrange(year,month)
返回两个整数。第一个是年度月(month
)的星期几的代码;第二个是当月的天数。表示星期几为0
(星期一)至6
(星期日);月份是1
到12
。
Prcal
(year,w = 2,l = 1,c = 6)
类似于:calendar.calendar(year
,
w
,
l
,
c)
的打印。
Prmonth
(year,month,w = 2,l = 1)
类似于:calendar.month(year,month,w,l)
的打印。
setfirstweekday(weekday)
将每周的第一天设置为星期几的代码。星期几的代码为0
(星期一)至6
(星期日)。
timegm(tupletime)
time.gmtime
的倒数:以时间元组的形式接受时刻,并返回与从时代(epoch
)开始的浮点数相同的时刻。
weekday(year,month,day)
返回给定日期的星期几的代码。星期几的代码为0
(星期一)至6
(星期日);月数是1
(1月)到12
(12月)。
calendar模块示例
# coding=utf-8'''Created on 2017年8月27日 @author: zxt'''importcalendar # 获取一个月的日历cal = calendar.month(2017, 8);print("Here is the calendar:");print(cal);
datetime
模块
datetime是Python处理日期和时间的标准库。需要注意的是,datetime是一个模块,这个模块里面有datetime类,此外常用的还有date类,以及time类。
datetime模块使用实例:
# coding=utf-8'''Created on 2017年8月27日 @author: zxt'''fromdatetime importdatefromdatetime importdatetimefromdatetime importtimedelta # 计算两个日期相差多少天d1 = date(2018, 10, 18);d2 = date(2017, 12, 31); print("(2018, 10, 18)与(2017, 12, 31)相差:", (d1 - d2).days, "天!"); # 获取两个日期时间的时间差time1 = datetime(2019, 1, 13, 12, 0, 0);time2 = datetime.now();differtime = (time1 -time2).total_seconds();# 输出结果print("(2019,1,13,12,0,0)与当前时间相差:", differtime, "秒!"); # 当前日期curdate = date.today();print("curdate =",curdate); # 计算十天之后的日期时间nowday = datetime.now();# timedelta类可以很容易地算出前几天和后几天的时刻。(timedelta(days= d, hours= h))# 还可以查看第几周对应的时间,例如:timedelta(weeks=20) 20周将被自动转化为天数# 前几天时刻,用减法。 后几天时刻,则用当前时间加上timedelta(days = d, hours= h)lastday = nowday + timedelta(days=10);print(str(lastday));# ctime() 返回一个表示日期和时间的字符串。print(lastday.ctime()); # 查看某一天是今年的第几天和第几周testday = date(2017, 8, 31);# isocalendar() 函数返回三元组 分别为:年份,周数,周几print(testday.isocalendar());# timetuple() 返回时间元祖print(testday.timetuple());
其他程序实例:
计算程序运行时间
# coding=utf-8'''Created on 2017年8月27日 @author: zxt'''# 统计程序运行时间的程序 importtime# datetime是一个模块,模块里面有一个datetime类,所以可以from datetime importdatetimeimportdatetime # 方法一(性能最差)starttime = datetime.datetime.now();time.sleep(2);endtime = datetime.datetime.now(); print((endtime - starttime).seconds) # 方法二start = time.time();time.sleep(2);end = time.time(); print(end- start); # 方法1和方法2都包含了其他程序使用CPU的时间,是程序开始到程序结束的运行时间。 # 推荐方法# 方法3 (只计算了程序运行的CPU时间)first = time.clock();time.sleep(2);second = time.clock(); print(second- first); # 要实现跨平台的精度性,也可以使用timeit 来代替time.importtimeit starttime2 = timeit.default_timer();time.sleep(2);endtime2 = timeit.default_timer(); print(str(endtime2 - starttime2));
- Python时间与日期操作(datetime、time、calendar)
- time,datetime------python操作日期和时间的方法
- Python标准库02 时间与日期 (time, datetime包)
- Python标准库02 时间与日期 (time, datetime包)
- Python标准库02 时间与日期 (time, datetime包)
- Python标准库02 时间与日期 (time, datetime包)
- Python标准库11 时间与日期 (time, datetime包)
- Python标准库02 时间与日期 (time, datetime包)
- python学习笔记23(时间与日期 (time, datetime包))
- python 时间模块 time 与 datetime 小结
- 2.Python标准库_ 时间与日期 (time, datetime包)
- python time,datetime 操作
- python基础篇--time,datetime(日期和时间)
- python 时间模块(time and datetime)
- Python学习笔记9:标准库之日期时间(time包,datetime包)
- python模块系列之 - time,datetime,calendar
- Python-time与datetime
- Python---time与datetime
- ASP.NET证控件的使用方法
- 【Git】2.Git常用指令
- R:使用R内置的mtcars数据框生成散点图及拟合曲线
- maven 打包Scala代码到jar包
- 浏览器出现Cannot set property 'onclick' of null的问题
- Python时间与日期操作(datetime、time、calendar)
- 李炎恢bootstrap写首页内容上思路解析
- nth-child()与nth-of-type()区别
- Java 内存模型
- Container With Most Water
- 如何修改MFC主窗口的大小
- 实现ViewPager懒加载的三种方法
- Java静态代理和动态代理的简单代码实现。
- CORS跨域资源共享你该知道的事儿