python time 模块

time 模块主要包含两种时间,一种是 UTC 时间,一种是本地时间。
UTC 时间可以通过 gmtime 调用。

import time
time.gmtime()
>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=11, tm_hour=7, tm_min=58, tm_sec=38, tm_wday=3, tm_yday=284, tm_isdst=0)

本地时间可以通过 localtime 调用。

import time
time.localtime()
>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=11, tm_hour=15, tm_min=59, tm_sec=34, tm_wday=3, tm_yday=284, tm_isdst=0)

相关函数

  • time() ,返回 UTC 时间的秒数,该数是浮点数
import time
time.time()
>>>  1539244967.6424007
  • clock(),以浮点数形式返回进程开始时的 CPU 时间。计算程序耗时,使用 clock() 更加精确。
import time

def procedure():
    time.sleep(2.5)

def calc_procedure():
    t0 = time.clock()
    procedure()
    cost_time = time.clock() - t0
    print(cost_time)

calc_procedure()
>>> 2.4999686415654168
  • sleep(), 参数为延迟的秒数,浮点数形式。JS 里面是毫秒。不同的预设,应该与这门语言最初设计的场景有关。
  • gmtime, 把秒数转化为 UTC 元组(tuple)形式
  • localtime, 把秒数转化为本地元组(tuple)
  • asctime, 把时间元组以字符串的形式输出。不传参数时,默认是本地时间元组。
import time
time.asctime(time.gmtime())
>>> 'Thu Oct 11 08:16:38 2018'
time.asctime()
>>> Thu Oct 11 16:14:08 2018
  • ctime, 把以秒计算的时间转化为字符串。不传参数也可以
time.ctime()
>>> 'Thu Oct 11 16:14:08 2018'
  • mktime, 把本地时间元组转化为时间戳。
time.mktime(time.localtime())
>>> 1539246152.0
  • strftime() 把时间元组转化为指定的形式(string format time)
# 传1个参数时默认是本地时间
time.strftime("%Y/%m/%d %H:%M-%S")
>>> '2018/10/11 16:24-24'
# 第2个参数可以是指定的时间元组
time.strftime("%Y/%m/%d %H:%M-%S", time.gmtime())
>>> '2018/10/11 08:25-09'
  • strptime 根据给定的形式,把字符串抽取成时间元组
time.strptime("2018/10/11 08:25-09", "%Y/%m/%d %H:%M-%S")

你可能感兴趣的:(python time 模块)