Python中的日期和时间(二)time和calendar模块

Python实用教程_spiritx的博客-CSDN博客 

time模块

time 模块既有时间处理的,也有转换时间格式的。time模块有许多UNIX和C的痕迹,它们很像的与UNIX和C的函数,可以和C进行通用。理解上如果对C不是很了解,可能会存在一些困难,在写C接口时,可能会用到它们,其他场景建议不要直接使用,以免出现问题难以解决。

重要属性

time.timezone

本地时区(未启动夏令时)距离格林威治的偏移秒数(>0,美洲;<=0大部分欧洲,亚洲,非洲)。

time.tzname

返回一个元组,即(所在标准时间区的名字,夏令时区名字)

time.altzone

返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值(如西欧,包括英国)。对夏令时启用地区才能使用。

>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800 

time.daylight

本地时间是否是夏令时间

>>> import time
>>> time.daylight
0

常用方法

time.time( )

返回当前时间的时间戳(1970纪元后经过的浮点秒数)。

>>> import time
>>> time.time()
1694098216.907698

time.localtime([secs])

不带参数是获取当前时间的时间元组:

>>> time.localtime()
time.struct_time(tm_year=2023, tm_mon=9, tm_mday=7, tm_hour=22, tm_min=48, tm_sec=2, tm_wday=3, tm_yday=250, tm_isdst=0)

接收时间戳(如time.time()返回的值)并返回当地时间下的时间元组

>>> import time
>>> time.localtime(1694098216.907698)
time.struct_time(tm_year=2023, tm_mon=9, tm_mday=7, tm_hour=22, tm_min=50, tm_sec=16, tm_wday=3, tm_yday=250, tm_isdst=0)

time.gmtime([secs])

接收时间戳并返回格林威治天文时间下的时间元组

>>> import time
>>> time.gmtime(time.time())
time.struct_time(tm_year=2023, tm_mon=9, tm_mday=7, tm_hour=14, tm_min=53, tm_sec=45, tm_wday=3, tm_yday=250, tm_isdst=0)

time.mktime(tupletime)

接受时间元组并返回时间戳(1970纪元后经过的浮点秒数)。

>>> time.mktime(time.localtime())
1694098540.0

time.asctime([tupletime])

将时间元组转化为字符串

>>> import time
>>> t = time.localtime()
>>> print ("time.asctime(t): %s " % time.asctime(t))
time.asctime(t): Thu Sep  7 22:59:41 2023 

如果不带参数,直接将当前时间转化为字符串:

>>> time.asctime()
'Thu Sep  7 23:01:00 2023'

time.ctime([secs])

将时间戳转化为字符串,相当于是time.asctime(time.localtime([secs])
如果未给定时间戳,就是当前时间

>>> import time
>>> time.time()
1694099035.372949
>>> time.ctime()
'Thu Sep  7 23:04:05 2023'
>>> time.ctime(1694099035.372949)
'Thu Sep  7 23:03:55 2023'

time.sleep(secs)
推迟调用线程的运行,secs指秒数。

import time

print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())

time.strftime(fmt[,tupletime])

接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。

>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016-04-07 11:18:05

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

根据fmt的格式把一个时间字符串解析为时间元组。

>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("返回元组: ", struct_time)
返回元组:  time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

time.tzset()

根据环境变量TZ重新初始化时间相关设置。

time.perf_counter()

返回计时器的精准时间(系统的运行时间),包含整个系统的睡眠时间。由于返回值的基准点是未定义的,所以,只有连续调用的结果之间的差才是有效的。

import time

scale = 50 

print("执行开始".center(scale//2,"-"))  # .center() 控制输出的样式,宽度为 25//2,即 22,汉字居中,两侧填充 -

start = time.perf_counter() # 调用一次 perf_counter(),从计算机系统里随机选一个时间点A,计算其距离当前时间点B1有多少秒。当第二次调用该函数时,默认从第一次调用的时间点A算起,距离当前时间点B2有多少秒。两个函数取差,即实现从时间点B1到B2的计时功能。
for i in range(scale+1):   
    a = '*' * i             # i 个长度的 * 符号
    b = '.' * (scale-i)  # scale-i) 个长度的 . 符号。符号 * 和 . 总长度为50 
    c = (i/scale)*100  # 显示当前进度,百分之多少
    dur = time.perf_counter() - start    # 计时,计算进度条走到某一百分比的用时
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')  # \r用来在每次输出完成后,将光标移至行首,这样保证进度条始终在同一行输出,即在一行不断刷新的效果;{:^3.0f},输出格式为居中,占3位,小数点后0位,浮点型数,对应输出的数为c;{},对应输出的数为a;{},对应输出的数为b;{:.2f},输出有两位小数的浮点数,对应输出的数为dur;end='',用来保证不换行,不加这句默认换行。
    time.sleep(0.1)     # 在输出下一个百分之几的进度前,停止0.1秒
print("\n"+"执行结果".center(scale//2,'-'))

time.perf_counter_ns()

与time.perf_counter()用法一样,但时间上精确到纳秒

>>> time.perf_counter_ns()
78724518597220
>>> time.perf_counter()
78727.953504732

time.process_time()

返回当前进程执行 CPU 的时间总和(以秒为单位时间的浮点值),不包含睡眠时间。由于返回值的基准点是未定义的,所以,只有连续调用的结果之间的差才是有效的。

# Python program to show time by process_time()  
from time import process_time 
  
# assigning n = 50  
n = 50 
  
# Start the stopwatch / counter  
t1_start = process_time()  
   
for i in range(n):
    print(i, end =' ') 
  
print()  
  
# Stop the stopwatch / counter 
t1_stop = process_time() 
   
print("Elapsed time:", t1_stop, t1_start)  
   
print("Elapsed time during the whole program in seconds:", t1_stop-t1_start) 

time.process_time_ns()

与time.process_time()用法一致,但是时间采用纳秒

>>> time.process_time_ns()
146499000
>>> time.process_time()
0.147873

日历模块

此模块的函数都是日历相关的,例如打印某月的字符月历。

星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。

函数及描述
calendar.calendar(year,w=2,l=1,c=6)
返回一个多行字符串格式的 year 年年历,3 个月一行,间隔距离为 c。 每日宽度间隔为w字符。每行长度为 21* W+18+2* C。l 是每星期行数。
calendar.firstweekday( )
返回当前每周起始日期的设置。默认情况下,首次载入 calendar 模块时返回 0,即星期一。
calendar.isleap(year)

是闰年返回 True,否则为 False。

>>> import calendar
>>> print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
False
calendar.leapdays(y1,y2)
返回在Y1,Y2两年之间的闰年总数。
calendar.month(year,month,w=2,l=1)
返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
calendar.monthcalendar(year,month)
返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
calendar.monthrange(year,month)

返回两个整数。第一个是该月的星期几,第二个是该月有几天。星期几是从0(星期一)到 6(星期日)。

>>> import calendar
>>> calendar.monthrange(2014, 11)
(5, 30)

(5, 30)解释:5 表示 2014 年 11 月份的第一天是周六,30 表示 2014 年 11 月份总共有 30 天。

calendar.prcal(year, w=0, l=0, c=6, m=3)
相当于 print (calendar.calendar(year, w=0, l=0, c=6, m=3))。
calendar.prmonth(theyear, themonth, w=0, l=0)
相当于 print(calendar.month(theyear, themonth, w=0, l=0))。
calendar.setfirstweekday(weekday)
设置每周的起始日期码。0(星期一)到6(星期日)。
calendar.timegm(tupletime)
和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间戳(1970纪元后经过的浮点秒数)。
calendar.weekday(year,month,day)
返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。
#!/usr/bin/python

import time
import calendar


# (1)当前时间戳
time.time()
# 1538271871.226226


# (2)时间戳 → 时间元组,默认为当前时间
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=3, tm_hour=9, tm_min=4, tm_sec=1, tm_wday=6, tm_yday=246, tm_isdst=0)
time.localtime()
time.localtime(1538271871.226226)


# (3)时间戳 → 可视化时间
# time.ctime(时间戳),默认为当前时间
time.ctime(1538271871.226226)


# (4)时间元组 → 时间戳
# 1538271871
time.mktime((2018, 9, 30, 9, 44, 31, 6, 273, 0))


# (5)时间元组 → 可视化时间
# time.asctime(时间元组),默认为当前时间
time.asctime()
time.asctime((2018, 9, 30, 9, 44, 31, 6, 273, 0))
time.asctime(time.localtime(1538271871.226226))


# (6)时间元组 → 可视化时间(定制)
# time.strftime(要转换成的格式,时间元组)
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


# (7)可视化时间(定制) → 时间元祖
# time.strptime(时间字符串,时间格式)
print(time.strptime('2018-9-30 11:32:23', '%Y-%m-%d %H:%M:%S'))


# (8)浮点数秒数,用于衡量不同程序的耗时,前后两次调用的时间差
time.clock()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值