Python

import time
import functools

def exec_time(func):
    def wrapper(*args, **kw):
        print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        return func(*args, **kw)
    return wrapper

@exec_time
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

print("=====================")

def exec_time(text):
    def deractor(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print(time.strftime(text, time.localtime(time.time())))
            return func(*args, **kw)
        return wrapper
    return deractor

@exec_time('%Y-%m-%d')
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

print("=====================")

def exec_time(text):
    def deractor(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print("begin time:", time.strftime(text, time.localtime(time.time())))
            t = func(*args, **kw)
            print("end time:", time.strftime(text, time.localtime(time.time())))
            return t;
        return wrapper
    return deractor

@exec_time('%Y-%m-%d %H:%M:%S')
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

output:

2017-12-03 20:50:00
test function...
wrapper
=====================
2017-12-03
test function...
testfunc
=====================
begin time: 2017-12-03 20:50:00
test function...
end time: 2017-12-03 20:50:00
testfunc
原文地址:https://www.cnblogs.com/hfultrastrong/p/7967214.html