1、简介

在编写测试脚本中,因涉及时间、日期、时间戳的相互转换。

2、引入模块:

1 # 引入模块
2 import time,datetime

2.1、str类型的日期转换为时间戳

1 # 字符类型的时间
 2 tss1 = '2020-01-10 23:40:00'
 3 # 转为时间数组
 4 timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
 5 print(timeArray)
 6 # timeArray可以调用tm_year等
 7 print(timeArray.tm_year)   # 2020
 8 # 转为时间戳
 9 # timeStamp = int(time.mktime(timeArray))  #秒转换
10 timeStamp = int(time.mktime(timeArray)*1000) #毫秒转换
11 print(timeStamp)  # 1578670800000
12 
13 
14 
15 # 结果如下
16 time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=10, tm_isdst=-1)
17 2020
18 1578670800000

2.2、更改str类型日期的显示格式

1 tss2 = "2020-01-10 23:40:00"
 2 # 转为数组
 3 timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")
 4 print(timeArray)
 5 # 转为其它显示格式
 6 otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
 7 print(otherStyleTime) # 2020/01/10 23:40:00
 8 
 9 # 结果如下
10 time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=10, tm_isdst=-1)
11 2020/01/10 23:40:00

2.3 时间戳转换为指定格式的日期

1 # 使用time
 2 timeStamp = 1578670800
 3 timeArray = time.localtime(timeStamp)
 4 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
 5 print(otherStyleTime)   # 2020--01--10 23:40:00
 6 # 使用datetime
 7 timeStamp = 1578670800
 8 dateArray = datetime.datetime.fromtimestamp(timeStamp)
 9 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
10 print(otherStyleTime)   # 2020--01--10 23:40:00
11 # 使用datetime,指定utc时间,相差8小时
12 timeStamp = 1578670800
13 dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
14 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
15 print(otherStyleTime)   # 2020--01--10 23:40:00

2.4 获取当前时间并且用指定格式显示

1 # time获取当前时间戳
 2 now = int(time.time())
 3 timeArray = time.localtime(now)
 4 print(timeArray)
 5 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
 6 print(otherStyleTime)
 7 
 8 # 结果如下
 9 time.struct_time(tm_year=2021, tm_mon=1, tm_mday=25, tm_hour=16, tm_min=50, tm_sec=10, tm_wday=0, tm_yday=25, tm_isdst=0)
10 2021--01--25 16:50:10
11 
12 
13 # datetime获取当前时间,数组格式
14 now = datetime.datetime.now()
15 print(now)
16 otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
17 print(otherStyleTime)
18 
19 # 结果如下:
20 2021-01-25 16:50:10.210738
21 2021--01--25 16:50:10