Python之time模块的使用

time模块的作用

  由底层C库提供与时间相关的函数。它包含一些函数,可以用于获取时钟时间和处理器运行的时间,还提供了基本的解析字符串格式化工具。

 1、使用get_clock_info()访问关于当前实现的基本信息,包括时钟的分辨率。

import textwrap
import time

available_clocks = [
    ('monotonic', time.monotonic),
    ('perf_counter', time.perf_counter),
    ('process_time', time.process_time),
    ('time', time.time),
]

for clock_name, func in available_clocks:
    print(textwrap.dedent('''
    {name}:
        adjustable    : {info.adjustable}
        implementation: {info.implementation}
        monotonic     : {info.monotonic}
        resolution    : {info.resolution}
        current       : {current}
    ''').format(
        name=clock_name,
        info=time.get_clock_info(clock_name),
        current=func())
    )
time_get_clock_info.py

运行效果

monotonic:
    adjustable    : False
    implementation: GetTickCount64()
    monotonic     : True
    resolution    : 0.015625
    current       : 17853.125


perf_counter:
    adjustable    : False
    implementation: QueryPerformanceCounter()
    monotonic     : True
    resolution    : 1e-07
    current       : 0.1238923


process_time:
    adjustable    : False
    implementation: GetProcessTimes()
    monotonic     : True
    resolution    : 1e-07
    current       : 0.125


time:
    adjustable    : True
    implementation: GetSystemTimeAsFileTime()
    monotonic     : False
    resolution    : 0.015625
    current       : 1589869261.2635095

 2、获取当前的时间戳(1970年1月1日 0:0)

import time

print('The time is:', time.time())
time_time.py

运行效果

The time is: 1589869885.7826087

3、时间的加减运算

import time

print('当前时间:', time.ctime())

later = time.time() + 15

print('15秒后的时间', time.ctime(later))
time_ctime.py

运行效果

当前时间: Tue May 19 14:43:54 2020
15秒后的时间 Tue May 19 14:44:09 2020

 4、不受修改系统时间,而且影响获取两个时间的时长的示例

import time

start = time.monotonic()
time.sleep(0.1)
end = time.monotonic()
print('start : {:>9.2f}'.format(start))
print('end   : {:>9.2f}'.format(end))
print('span  : {:>9.2f}'.format(end - start))
time_monotonic.py

运行效果

start :  19804.80
end   :  19804.89
span  :      0.09

 5、处理器时钟时间打印示例

import hashlib
import time

# 数据进行md5校验
data = open(__file__, 'rb').read()

for i in range(5):
    h = hashlib.sha1()
    print('当前的美式时间:', time.ctime(), ': 当前时间戳:{:0.3f} 处理时长:{:0.3f}'.format(
        time.time(), time.process_time()))
    for i in range(300000):
        h.update(data)
    cksum = h.digest()
time_process_time.py

运行效果

当前的美式时间: Tue May 19 14:59:42 2020 : 当前时间戳:1589871582.797 处理时长:0.047
当前的美式时间: Tue May 19 14:59:43 2020 : 当前时间戳:1589871583.017 处理时长:0.266
当前的美式时间: Tue May 19 14:59:43 2020 : 当前时间戳:1589871583.220 处理时长:0.484
当前的美式时间: Tue May 19 14:59:43 2020 : 当前时间戳:1589871583.423 处理时长:0.672
当前的美式时间: Tue May 19 14:59:43 2020 : 当前时间戳:1589871583.632 处理时长:0.891

6、睡眠clock()的时间不会增加,而time.time()时间会迭增的示例

import time

template = '{} - {:0.2f} - {:0.2f}'

print(template.format(
    time.ctime(), time.time(), time.process_time())
)

for i in range(3, 0, -1):
    print('Sleeping', i)
    time.sleep(i)
    print(template.format(
        time.ctime(), time.time(), time.process_time())
    )
time_clock_sleep.py

 运行效果

Tue May 19 15:05:25 2020 - 1589871925.70 - 0.03
Sleeping 3
Tue May 19 15:05:28 2020 - 1589871928.70 - 0.03
Sleeping 2
Tue May 19 15:05:30 2020 - 1589871930.70 - 0.03
Sleeping 1
Tue May 19 15:05:31 2020 - 1589871931.70 - 0.03

 7、性能计数器(计数循环开始,到循环里面的运行时间)

import hashlib
import time

# Data to use to calculate md5 checksums
data = open(__file__, 'rb').read()

loop_start = time.perf_counter()
for i in range(5):
    iter_start = time.perf_counter()
    h = hashlib.sha1()
    for i in range(300000):
        h.update(data)
    cksum = h.digest()
    now = time.perf_counter()
    loop_elapsed = now - loop_start
    iter_elapsed = now - iter_start
    print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
        iter_elapsed, loop_elapsed))
time_perf_counter.py

运行效果

Tue May 19 15:27:13 2020 : 0.258 0.258
Tue May 19 15:27:13 2020 : 0.289 0.546
Tue May 19 15:27:13 2020 : 0.267 0.813
Tue May 19 15:27:14 2020 : 0.264 1.077
Tue May 19 15:27:14 2020 : 0.252 1.330

 8、获取当前时间的年、月、日、时、分、秒的数据

import time


def show_struct(s):
    print('  tm_year :', s.tm_year)
    print('  tm_mon  :', s.tm_mon)
    print('  tm_mday :', s.tm_mday)
    print('  tm_hour :', s.tm_hour)
    print('  tm_min  :', s.tm_min)
    print('  tm_sec  :', s.tm_sec)
    print('  tm_wday :', s.tm_wday)
    print('  tm_yday :', s.tm_yday)
    print('  tm_isdst:', s.tm_isdst)


print('gmtime UTC格式时间:')
show_struct(time.gmtime())
print('\nlocaltime 获取本地的时区时间:')
show_struct(time.localtime())
print('\nmktime 将当前时间转为浮点显示:', time.mktime(time.localtime()))
time_struct.py

运行效果

gmtime UTC格式时间:
  tm_year : 2020
  tm_mon  : 5
  tm_mday : 19
  tm_hour : 7
  tm_min  : 40
  tm_sec  : 30
  tm_wday : 1
  tm_yday : 140
  tm_isdst: 0

localtime 获取本地的时区时间:
  tm_year : 2020
  tm_mon  : 5
  tm_mday : 19
  tm_hour : 15
  tm_min  : 40
  tm_sec  : 30
  tm_wday : 1
  tm_yday : 140
  tm_isdst: 0

mktime 将当前时间转为浮点显示: 1589874030.0

 9、不同的时区,获取不相同的时间【只有在linux生效,windows只能使用localtime()】

import os
import time


def show_zone_info():
    print('  TZ    :', os.environ.get('TZ', '(not set)'))
    print('  tzname:', time.tzname)
    print('  Zone  : {} ({})'.format(
        time.timezone, (time.timezone / 3600)))
    print('  DST   :', time.daylight)
    print('  Time  :', time.ctime())
    print()


print('Default :')
show_zone_info()

ZONES = [
    'GMT',
    'Europe/Amsterdam',
]

for zone in ZONES:
    os.environ['TZ'] = zone
    time.tzset()
    time.tzset()
    print(zone, ':')
    show_zone_info()
time.localtime()
time_timezone.py

运行效果

[root@localhost ~]# python3 time_timezone.py
Default :
  TZ    : (not set)
  tzname: ('CST', 'CST')
  Zone  : -28800 (-8.0)
  DST   : 0
  Time  : Tue May 19 17:30:59 2020

GMT :
  TZ    : GMT
  tzname: ('GMT', 'GMT')
  Zone  : 0 (0.0)
  DST   : 0
  Time  : Tue May 19 09:30:59 2020

Europe/Amsterdam :
  TZ    : Europe/Amsterdam
  tzname: ('CET', 'CEST')
  Zone  : -3600 (-1.0)
  DST   : 1
  Time  : Tue May 19 11:30:59 2020

10、时间的解析和格式化

import time


def show_struct(s):
    print('  tm_year :', s.tm_year)
    print('  tm_mon  :', s.tm_mon)
    print('  tm_mday :', s.tm_mday)
    print('  tm_hour :', s.tm_hour)
    print('  tm_min  :', s.tm_min)
    print('  tm_sec  :', s.tm_sec)
    print('  tm_wday :', s.tm_wday)
    print('  tm_yday :', s.tm_yday)
    print('  tm_isdst:', s.tm_isdst)


now = time.ctime(1483391847.433716)
print('Now:', now)

parsed = time.strptime(now)
print('\nParsed:')
show_struct(parsed)

print('\nFormatted:',
      time.strftime("%a %b %d %H:%M:%S %Y", parsed))
time_strptime.py

 

 运行效果

Now: Tue Jan  3 05:17:27 2017

Parsed:
  tm_year : 2017
  tm_mon  : 1
  tm_mday : 3
  tm_hour : 5
  tm_min  : 17
  tm_sec  : 27
  tm_wday : 1
  tm_yday : 3
  tm_isdst: -1

Formatted: Tue Jan 03 05:17:27 2017
posted @ 2020-05-19 17:44  小粉优化大师  阅读(555)  评论(0编辑  收藏  举报