python标准库实例详解八

发布时间:2019-07-31编辑:脚本学堂
本节是python标准库实例教程的第八节,学习下python模块sys、string、time等的用法,有需要的朋友参考下。
strptime 不完全实现
 

复制代码 代码示例:
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>dd?)",
    "%d": "(?P<day>dd?)",
    "%D": "(?P<month>dd?)/(?P<day>dd?)/(?P<year>dd)",
    "%e": "(?P<day>dd?)",
    "%h": "(?P<month>[a-z]+)",
    "%H": "(?P<hour>dd?)",
    "%I": "(?P<hour12>dd?)",
    "%j": "(?P<yearday>dd?d?)",
    "%m": "(?P<month>dd?)",
    "%M": "(?P<minute>dd?)",
    "%p": "(?P<ampm12>am|pm)",
    "%R": "(?P<hour>dd?):(?P<minute>dd?)",
    "%S": "(?P<second>dd?)",
    "%T": "(?P<hour>dd?):(?P<minute>dd?):(?P<second>dd?)",
    "%U": "(?P<week>dd)",
    "%w": "(?P<weekday>d)",
    "%W": "(?P<weekday>dd)",
    "%y": "(?P<year>dd)",
    "%Y": "(?P<year>dddd)",
    "%%": "%"
}
 
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()))
 
(2000, 12, 20, 1, 2, 3, 0, 0, 0)
(2000, 11, 15, 12, 30, 45, 0, 0, 0)
 

使用 time 模块将本地时间元组转换为时间值(整数)
 

复制代码 代码示例:
import time
 
t0 = time.time()
tm = time.localtime(t0)
 
print tm
 
print t0
print time.mktime(tm)
 
(1999, 9, 9, 0, 11, 8, 3, 252, 1)
936828668.16
936828668.0
 

将 UTC 时间元组转换为时间值(整数)
 

复制代码 代码示例:
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)
 
(1999, 9, 8, 22, 12, 12, 2, 251, 0)
936828732.48
936828732
 

  
使用 time 模块评价算法
 

复制代码 代码示例:
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"
 
0.0 seconds process time
2.50903499126 seconds wall time
 

  
使用 types 模块
 

复制代码 代码示例:
import types
 
def check(object):
    print object,
 
    if type(object) is types.IntType:
        print "INTEGER",
    if type(object) is types.FloatType:
        print "FLOAT",
    if type(object) is types.StringType:
        print "STRING",
    if type(object) is types.ClassType:
        print "CLASS",
    if type(object) is types.InstanceType:
        print "INSTANCE",
    print
 
check(0)
check(0.0)
check("0")
 
class A:
    pass
 
class B:
    pass
 
check(A)
check(B)
 
a = A()
b = B()
 
check(a)
check(b)
 
0 INTEGER
0.0 FLOAT
0 STRING
A CLASS
B CLASS
<A instance at 796960> INSTANCE
<B instance at 796990> INSTANCE
 

  
使用 gc 模块收集循环引用垃圾
 

复制代码 代码示例:
import gc
 
# create a simple object that links to itself
class Node:
 
    def _ _init_ _(self, name):
        self.name = name
        self.parent = None
        self.children = []
 
    def addchild(self, node):
        node.parent = self
        self.children.append(node)
 
    def _ _repr_ _(self):
        return "<Node %s at %x>" % (repr(self.name), id(self))
 
# set up a self-referencing structure
root = Node("monty")
 
root.addchild(Node("eric"))
root.addchild(Node("john"))
root.addchild(Node("michael"))
 
# remove our only reference
del root
 
print gc.collect(), "unreachable objects"
print gc.collect(), "unreachable objects"
 
12 unreachable objects
0 unreachable objects