==time 模块==

``time`` 模块提供了一些处理日期和一天内时间的函数. 它是建立在 C 运行时库的简单封装. 

给定的日期和时间可以被表示为浮点型(从参考时间, 通常是 1970.1.1 到现在经过的秒数.
即 Unix 格式), 或者一个表示时间的 struct (类元组). === 获得当前时间=== [Example 1-79 #eg-1-79] 展示了如何使用 ``time`` 模块获取当前时间. ====Example 1-79. 使用 time 模块获取当前时间====[eg-1-79] ```
File: time-example-1.py import time now = time.time() print now, "seconds since", time.gmtime(0)[:6]
print
print "or in other words:"
print "- local time:", time.localtime(now)
print "- utc:", time.gmtime(now) *B*937758359.77 seconds since (1970, 1, 1, 0, 0, 0) or in other words:
- local time: (1999, 9, 19, 18, 25, 59, 6, 262, 1)
- utc: (1999, 9, 19, 16, 25, 59, 6, 262, 0)*b*
``` ``localtime`` 和 ``gmtime`` 返回的类元组包括年, 月, 日, 时, 分, 秒, 星期, 一年的第几天, 日光标志.
其中年是一个四位数(在有千年虫问题的平台上另有规定, 但还是四位数), 星期从星期一(数字 0 代表)开始,
1月1日是一年的第一天. === 将时间值转换为字符串=== 你可以使用标准的格式化字符串把时间对象转换为字符串, 不过 ``time`` 模块已经提供了许多标准转换函数,
如 [Example 1-80 #eg-1-80] 所示. ====Example 1-80. 使用 time 模块格式化时间输出====[eg-1-80] ```
File: time-example-2.py import time now = time.localtime(time.time()) print time.asctime(now)
print time.strftime("%y/%m/%d %H:%M", now)
print time.strftime("%a %b %d", now)
print time.strftime("%c", now)
print time.strftime("%I %p", now)
print time.strftime("%Y-%m-%d %H:%M:%S %Z", now) # do it by hand...
year, month, day, hour, minute, second, weekday, yearday, daylight = now
print "%04d-%02d-%02d" % (year, month, day)
print "%02d:%02d:%02d" % (hour, minute, second)
print ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")[weekday], yearday *B*Sun Oct 10 21:39:24 1999
99/10/10 21:39
Sun Oct 10
Sun Oct 10 21:39:24 1999
09 PM
1999-10-10 21:39:24 CEST
1999-10-10
21:39:24
SUN 283*b*
``` ===将字符串转换为时间对象=== 在一些平台上, ``time`` 模块包含了 ``strptime`` 函数, 它的作用与 ``strftime`` 相反.
给定一个字符串和模式, 它返回相应的时间对象, 如 [Example 1-81 #eg-1-81] 所示. ====Example 1-81. 使用 time.strptime 函数解析时间====[eg-1-81] ```
File: time-example-6.py import time # make sure we have a strptime function!
# 确认有函数 strptime
try:
strptime = time.strptime
except AttributeError:
from strptime import strptime print strptime("31 Nov 00", "%d %b %y")
print strptime("1 Jan 70 1:30pm", "%d %b %y %I:%M%p")
``` 只有在系统的 C 库提供了相应的函数的时候, ``time.strptime`` 函数才可以使用.
对于没有提供标准实现的平台, [Example 1-82 #eg-1-82] 提供了一个不完全的实现. ====Example 1-82. strptime 实现====[eg-1-82] ```
File: strptime.py import re
import string MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"] SPEC = {
# map formatting code to a regular expression fragment
"%a": "(?P<weekday>[a-z]+)",
"%A": "(?P<weekday>[a-z]+)",
"%b": "(?P<month>[a-z]+)",
"%B": "(?P<month>[a-z]+)",
"%C": "(?P<century>\d\d?)",
"%d": "(?P<day>\d\d?)",
"%D": "(?P<month>\d\d?)/(?P<day>\d\d?)/(?P<year>\d\d)",
"%e": "(?P<day>\d\d?)",
"%h": "(?P<month>[a-z]+)",
"%H": "(?P<hour>\d\d?)",
"%I": "(?P<hour12>\d\d?)",
"%j": "(?P<yearday>\d\d?\d?)",
"%m": "(?P<month>\d\d?)",
"%M": "(?P<minute>\d\d?)",
"%p": "(?P<ampm12>am|pm)",
"%R": "(?P<hour>\d\d?):(?P<minute>\d\d?)",
"%S": "(?P<second>\d\d?)",
"%T": "(?P<hour>\d\d?):(?P<minute>\d\d?):(?P<second>\d\d?)",
"%U": "(?P<week>\d\d)",
"%w": "(?P<weekday>\d)",
"%W": "(?P<weekday>\d\d)",
"%y": "(?P<year>\d\d)",
"%Y": "(?P<year>\d\d\d\d)",
"%%": "%"
} class TimeParser:
def _ _init_ _(self, format):
# convert strptime format string to regular expression
format = string.join(re.split("(?:\s|%t|%n)+", format))
pattern = []
try:
for spec in re.findall("%\w|%%|.", format):
if spec[0] == "%":
spec = SPEC[spec]
pattern.append(spec)
except KeyError:
raise ValueError, "unknown specificer: %s" % spec
self.pattern = re.compile("(?i)" + string.join(pattern, ""))
def match(self, daytime):
# match time string
match = self.pattern.match(daytime)
if not match:
raise ValueError, "format mismatch"
get = match.groupdict().get
tm = [0] * 9
# extract date elements
y = get("year")
if y:
y = int(y)
if y < 68:
y = 2000 + y
elif y < 100:
y = 1900 + y
tm[0] = y
m = get("month")
if m:
if m in MONTHS:
m = MONTHS.index(m) + 1
tm[1] = int(m)
d = get("day")
if d: tm[2] = int(d)
# extract time elements
h = get("hour")
if h:
tm[3] = int(h)
else:
h = get("hour12")
if h:
h = int(h)
if string.lower(get("ampm12", "")) == "pm":
h = h + 12
tm[3] = h
m = get("minute")
if m: tm[4] = int(m)
s = get("second")
if s: tm[5] = int(s)
# ignore weekday/yearday for now
return tuple(tm) def strptime(string, format="%a %b %d %H:%M:%S %Y"):
return TimeParser(format).match(string) if _ _name_ _ == "_ _main_ _":
# try it out
import time
print strptime("2000-12-20 01:02:03", "%Y-%m-%d %H:%M:%S")
print strptime(time.ctime(time.time())) *B*(2000, 12, 20, 1, 2, 3, 0, 0, 0)
(2000, 11, 15, 12, 30, 45, 0, 0, 0)*b*
``` === 转换时间值=== 将时间元组转换回时间值非常简单, 至少我们谈论的当地时间 (local time) 如此.
只要把时间元组传递给 ``mktime`` 函数, 如 [Example 1-83 #eg-1-83] 所示. ====Example 1-83. 使用 time 模块将本地时间元组转换为时间值(整数)====[eg-1-83] ```
File: time-example-3.py import time t0 = time.time()
tm = time.localtime(t0) print tm print t0
print time.mktime(tm) *B*(1999, 9, 9, 0, 11, 8, 3, 252, 1)
936828668.16
936828668.0*b*
``` 但是, 1.5.2 版本的标准库没有提供能将 UTC 时间
(Universal Time, Coordinated: 特林威治标准时间)转换为时间值的函数
( Python 和对应底层 C 库都没有提供). [Example 1-84 #eg-1-84] 提供了该函数的一个
Python 实现, 称为 ``timegm`` . ====Example 1-84. 将 UTC 时间元组转换为时间值(整数)====[eg-1-84] ```
File: time-example-4.py import time def _d(y, m, d, days=(0,31,59,90,120,151,181,212,243,273,304,334,365)):
# map a date to the number of days from a reference point
return (((y - 1901)*1461)/4 + days[m-1] + d +
((m > 2 and not y % 4 and (y % 100 or not y % 400)) and 1)) def timegm(tm, epoch=_d(1970,1,1)):
year, month, day, h, m, s = tm[:6]
assert year >= 1970
assert 1 <= month <= 12
return (_d(year, month, day) - epoch)*86400 + h*3600 + m*60 + s t0 = time.time()
tm = time.gmtime(t0) print tm print t0
print timegm(tm) *B*(1999, 9, 8, 22, 12, 12, 2, 251, 0)
936828732.48
936828732*b*
``` 从 1.6 版本开始, ``calendar`` 模块提供了一个类似的函数 ``calendar.timegm`` . === Timing 相关=== ``time`` 模块可以计算 Python 程序的执行时间, 如 [Example 1-85 #eg-1-85] 所示.
你可以测量 "wall time" (real world time), 或是"进程时间" (消耗的 CPU 时间). ====Example 1-85. 使用 time 模块评价算法====[eg-1-85] ```
File: time-example-5.py import time def procedure():
time.sleep(2.5) # measure process time
t0 = time.clock()
procedure()
print time.clock() - t0, "seconds process time" # measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time" *B*0.0 seconds process time
2.50903499126 seconds wall time*b*
``` 并不是所有的系统都能测量真实的进程时间. 一些系统中(包括 Windows ),
``clock`` 函数通常测量从程序启动到测量时的 wall time. 进程时间的精度受限制. 在一些系统中, 它超过 30 分钟后进程会被清理.
(原文: On many systems, it wraps around after just over 30 minutes.) 另参见 ``timing`` 模块( Windows 下的朋友不用忙活了,没有地~), 它可以测量两个事件之间的 wall time.

  

python标准库介绍——12 time 模块详解的更多相关文章

  1. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

  2. python标准库介绍——10 sys 模块详解

    ==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...

  3. python标准库介绍——30 code 模块详解

    ==code 模块== ``code`` 模块提供了一些用于模拟标准交互解释器行为的函数. ``compile_command`` 与内建 ``compile`` 函数行为相似, 但它会通过测试来保证 ...

  4. python标准库介绍——14 gc 模块详解

    ==gc 模块== (可选, 2.0 及以后版本) ``gc`` 模块提供了到内建循环垃圾收集器的接口. Python 使用引用记数来跟踪什么时候销毁一个对象; 一个对象的最后一个引用一旦消失, 这个 ...

  5. python标准库介绍——8 operator 模块详解

    ==operator 模块== ``operator`` 模块为 Python 提供了一个 "功能性" 的标准操作符接口. 当使用 ``map`` 以及 ``filter`` 一类 ...

  6. python标准库介绍——36 popen2 模块详解

    ==popen2 模块== ``popen2`` 模块允许你执行外部命令, 并通过流来分别访问它的 ``stdin`` 和 ``stdout`` ( 可能还有 ``stderr`` ). 在 pyth ...

  7. python标准库介绍——23 UserString 模块详解

    ==UserString 模块== (2.0 新增) ``UserString`` 模块包含两个类, //UserString// 和 //MutableString// . 前者是对标准字符串类型的 ...

  8. python标准库介绍——22 UserList 模块详解

    ==UserList 模块== ``UserList`` 模块包含了一个可继承的列表类 (事实上是对内建列表类型的 Python 封装). 在 [Example 2-16 #eg-2-16] 中, / ...

  9. python标准库介绍——21 UserDict 模块详解

    ==UserDict 模块== ``UserDict`` 模块包含了一个可继承的字典类 (事实上是对内建字典类型的 Python 封装). [Example 2-15 #eg-2-15] 展示了一个增 ...

随机推荐

  1. TextBox_TextChanged

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = sender a ...

  2. FM同步数据库中结构已经发生变化的表

    接触Cognos很久了,最近遇到一个小问题. 在FM模型设计的过程中,有一张表jd_f_order.之后为了更全面的分析这个数据,在这个事实表中引入了一个新的字段商品类型字段,结构如图 但是由于jd_ ...

  3. 重命名IDEA14项目名

    Project Settings / Project ->">工程结构(ctrl-alt-shift-s)->设置->项目/项目Project name: 请注意,这 ...

  4. 【死磕Java并发】-----深入分析synchronized的实现原理

    记得刚刚開始学习Java的时候.一遇到多线程情况就是synchronized.相对于当时的我们来说synchronized是这么的奇妙而又强大,那个时候我们赋予它一个名字"同步". ...

  5. wepy - 入手

    wepy官方文档: https://tencent.github.io/wepy/document.html#/ ESLint:一般用来校验JavaScript代码是否符合规范,不符合预期就报错(程序 ...

  6. 线性表 顺序存储 链式存储 ---java实现

    首先抽象出一个线性表抽象类(包括主要的增删操作) public abstract class MyAbstractList<E> { public abstract void add(E ...

  7. Oracle查询备注信息

    查询表的备注信息: SELECT TABLE_NAME, TABLE_TYPE, COMMENTS FROM USER_TAB_COMMENTS WHERE TABLE_NAME = 'MR_DEPT ...

  8. How to set up OpenERP for various timezone kindly follow the following steps to select timezone in OpenERP

        How to set up OpenERP for different Time Zones Click on the "Edit Preferences" wheel a ...

  9. java 类名.class、object.getClass()和Class.forName()的区别 精析

        1.介绍 getClass()介绍 java是面向对象语言,即万物皆对象,所有的对象都直接或间接继承自Object类: Object类中有getClass()方法,通过这个方法就可以获得一个实 ...

  10. 【Python】学习笔记六:循环

    循环是一个结构,导致一个程序要重复一定的次数 条件循环也一样,当条件变为假,循环结束 For循环 在python for循环遍历序列,如一个列表或一个字符. for循环语法:   ——for iter ...