时间模块

5.15.2 时间模块

  • 日期和时间

与时间相关的操作,我们就需要使用到时间模块。

常用方法

import time

time.sleep()  # 推迟指定时间运行,单位为秒

time.time()  # 获取当前时间戳

在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:

  1. 时间戳(timestamp) :

通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

import time

print(time.time())
# 1681209459.990895
  1. 格式化的时间字符串(Format String): ‘1999-12-06’
python中时间日期格式化符号:

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
import time

print(time.strftime("%Y-%m-%d %x"))
# 2023-04-11 04/11/23

print(time.strftime("%Y-%m-%d %H-%M-%S"))
# 2023-04-11 10-40-23
  1. 元组(struct_time) :

struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2011
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 60
6 tm_wday(weekday) 0 - 6(0表示周一)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为0
import time

t = time.localtime()

print(t)
# time.struct_time(tm_year=2023, tm_mon=4, tm_mday=11, tm_hour=10, tm_min=44, tm_sec=24, tm_wday=1, tm_yday=101, tm_isdst=0)

时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的

时间格式的转换

  • 时间戳-->结构化时间
# time.gmtime(时间戳)    
# # UTC时间,与英国伦敦当地时间一致

# time.localtime(时间戳) 

# 当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间 

import time

print(time.time())

print(time.gmtime(1681210288))
# time.struct_time(tm_year=2023, tm_mon=4, tm_mday=11, tm_hour=10, tm_min=51, tm_sec=28, tm_wday=1, tm_yday=101, tm_isdst=0)

print(time.localtime(1681210288))
# time.struct_time(tm_year=2023, tm_mon=4, tm_mday=11, tm_hour=10, tm_min=51, tm_sec=28, tm_wday=1, tm_yday=101, tm_isdst=0)
  • 结构化时间-->时间戳
# time.mktime(结构化时间)
import time

time_tuple = time.localtime()

print(time.mktime(time_tuple))
# 1681210505.0

  • 结构化时间-->字符串时间
# time.strftime("格式定义","结构化时间")  
# 结构化时间参数若不传,则显示当前时间
import time

print(time.strftime("%Y-%m-%d %X"))
# 2023-04-11 10:57:01

print(time.strftime("%Y-%m-%d",time.localtime(1600000000)))
# 2020-09-13

字符串时间-->结构化时间

#time.strptime(时间字符串,字符串对应格式)
import time

print(time.strptime("2022-03-16","%Y-%m-%d"))
# time.struct_time(tm_year=2022, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=75, tm_isdst=-1)

print(time.strptime("07/24/2023","%m/%d/%Y"))
# time.struct_time(tm_year=2023, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)

  • 结构化时间 --> %a %b %d %H:%M:%S %Y串
#time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
import time

t = time.asctime(time.localtime(1650000000))
print(t)
# Fri Apr 15 05:20:00 2022

t2 = time.asctime()
print(t2)
# Tue Apr 11 11:02:07 2023
  • 时间戳 --> %a %d %d %H:%M:%S %Y串
#time.ctime(时间戳)  如果不传参数,直接返回当前时间的格式化串
import time

t1 = time.ctime()
print(t1)
# Tue Apr 11 11:05:15 2023
t2 = time.ctime(1657800000)
print(t2)
# Thu Jul 14 12:00:00 2022

t = time.time()
ft = time.ctime(t)
print(ft)
# Tue Apr 11 11:05:37 2023

st = time.localtime()
ft = time.asctime(st)
print(ft)
# Tue Apr 11 11:05:37 2023
  • time方法总结

1. time.altzone

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

以下实例展示了 altzone()函数的使用方法:

import time
print ("time.altzone %d " % time.altzone)
# time.altzone 0 

2. time.asctime([tupletime])

接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18时07分14秒)的24个字符的字符串。

以下实例展示了 asctime()函数的使用方法:

import time
t = time.localtime()
print ("time.asctime(t): %s " % time.asctime(t))
# time.asctime(t): Thu Apr  7 10:36:20 2016 

3. time.clock()

用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。

import time

def procedure():
    time.sleep(2.5)

# time.clock
t0 = time.clock()
procedure()
print (time.clock() - t0)

# time.time
t0 = time.time()
procedure()
print (time.time() - t0)

4. time.ctime([secs])

作用相当于asctime(localtime(secs)),未给参数相当于asctime()

以下实例展示了 ctime()函数的使用方法:

import time
print ("time.ctime() : %s" % time.ctime())
# time.ctime() : Thu Apr  7 10:51:58 2016

5. time.gmtime([secs])

接收时间辍(1970纪元后经过的浮点秒数)并返回格林威治天文时间下的时间元组t。注:t.tm_isdst始终为0

以下实例展示了 gmtime()函数的使用方法:

import time
print ("gmtime :", time.gmtime(1455508609.34375))
# gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)

6. time.localtime([secs]

接收时间辍(1970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)。

以下实例展示了 localtime()函数的使用方法:

import time
print ("localtime(): ", time.localtime(1455508609.34375))
# localtime():  time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)

7. time.mktime(tupletime)

time.mktime() 函数执行与gmtime(), localtime()相反的操作,它接收struct_time对象作为参数,返回用秒数来表示时间的浮点数。

如果输入的值不是一个合法的时间,将触发 OverflowError 或 ValueError。

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

import time

t = (2016, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )

print ("time.mktime(t) : %f" %  secs)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))

8. time.sleep(secs)

推迟调用线程的运行,secs指秒数。

以下实例展示了 sleep()函数的使用方法:

import time

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

9. time.strftime(fmt[,tupletime])

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

以下实例展示了 strftime()函数的使用方法:

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

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

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

以下实例展示了 strptime()函数的使用方法:

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)

11. time.time( )

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

以下实例展示了 time()函数的使用方法:

import time
print(time.time())
# 1459999336.1963577

12. time.tzset()

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

import time
import os

os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print (time.strftime('%X %x %Z'))

os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
time.tzset()
print (time.strftime('%X %x %Z'))
  • 日历(Calendar)模块

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

星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday() 函数。模块包含了以下内置函数:

1. calendar.calendar(year,w=2,l=1,c=6)

返回一个多行字符串格式的 year 年年历,3 个月一行,间隔距离为 c。 每日宽度间隔为 w 字符。每行长度为 21* W+18+2* C。l 是每星期行数。

2. calendar.firstweekday( )

返回当前每周起始日期的设置。默认情况下,首次载入 calendar 模块时返回 0,即星期一。

3. calendar.isleap(year)

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

4. calendar.leapdays(y1,y2)

返回在 Y1,Y2 两年之间的闰年总数。

5. calendar.month(year,month,w=2,l=1)

返回一个多行字符串格式的 year 年 month 月日历,两行标题,一周一行。每日宽度间隔为 w 字符。每行的长度为 7* w+6。l 是每星期的行数。

6. calendar.monthcalendar(year,month)

返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year 年 month 月外的日期都设为 0;范围内的日子都由该月第几日表示,从 1 开始。

7. calendar.monthrange(year,month)

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

8. calendar.prcal(year,w=2,l=1,c=6)

相当于 print(calendar.calendar(year,w,l,c)) .

9. calendar.prmonth(year,month,w=2,l=1)

相当于 print calendar.calendar(year,w,l,c)。

10. calendar.setfirstweekday(weekday)

设置每周的起始日期码。0(星期一)到 6(星期日)。

11. calendar.timegm(tupletime)

和 time.gmtime 相反:接受一个时间元组形式,返回该时刻的时间辍(1970 纪元后经过的浮点秒数)。

12. calendar.weekday(year,month,day)

返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。

  • datetime模块

datetime模块供应类操作日期和时间。日期和时间的算术支持时,实施的焦点是有效的输出格式和属性提取操作。

1.datetime.now() 获取当前datetime

datetime.utcnow() 获取当前格林威治时间

from datetime import datetime

#获取当前本地时间
a=datetime.now()
print('当前日期:',a)
# 当前日期: 2023-04-11 11:47:03.572452

#获取当前世界时间
b=datetime.utcnow()
print('世界时间:',b)
# 世界时间: 2023-04-11 11:47:03.572473

2.datetime(2023, 4, 11, 12, 20)用指定日期时间创建datetime

from datetime import datetime

#用指定日期创建
c=datetime(2023, 4, 11, 12, 20)
print('指定日期:',c)

3.将以下字符串转换成datetime类型:

'2017/9/30'

'2017年9月30日星期六'

'2017年9月30日星期六8时42分24秒'

'9/30/2017'

'9/30/2017 8:42:50 '

from datetime import datetime

d=datetime.strptime('2017/9/30','%Y/%m/%d')
print(d)

e=datetime.strptime('2017年9月30日星期六','%Y年%m月%d日星期六')
print(e)

f=datetime.strptime('2017年9月30日星期六8时42分24秒','%Y年%m月%d日星期六%H时%M分%S秒')
print(f)

g=datetime.strptime('9/30/2017','%m/%d/%Y')
print(g)

h=datetime.strptime('9/30/2017 8:42:50 ','%m/%d/%Y %H:%M:%S ')
print(h)

4.将以下datetime类型转换成字符串:

2017年9月28日星期4,10时3分43秒

Saturday, September 30, 2017

9/30/2017 9:22:17 AM

September 30, 2017

from datetime import datetime

i=datetime(2017,9,28,10,3,43)
print(i.strftime('%Y年%m月%d日%A,%H时%M分%S秒'))

j=datetime(2017,9,30,10,3,43)
print(j.strftime('%A,%B %d,%Y'))

k=datetime(2017,9,30,9,22,17)
print(k.strftime('%m/%d/%Y %I:%M:%S%p'))

l=datetime(2017,9,30)
print(l.strftime('%B %d,%Y'))

5.用系统时间输出以下字符串:

今天是2017年9月30日

今天是这周的第?天

今天是今年的第?天

今周是今年的第?周

今天是当月的第?天

from datetime import datetime

#获取当前系统时间
m=datetime.now()
print(m.strftime('今天是%Y年%m月%d日'))
print(m.strftime('今天是这周的第%w天'))
print(m.strftime('今天是今年的第%j天'))
print(m.strftime('今周是今年的第%W周'))
print(m.strftime('今天是当月的第%d天'))
posted @ 2023-04-13 23:06  WNAG_zw  阅读(36)  评论(0)    收藏  举报