定义:本质上是函数,(装饰其他函数)就是为其他函数添加附件功能
原则:
不能修改被装饰函数的源代码
不能修改被装饰函数的调用方式
举例:把current_time,还有distance_current_time合成一个函数和装饰器
#auther:Summer-yang
#datetime:2022/4/18 14:44
import datetime
import re
UTC_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
def current_time(hours=None,time_format = None):
"""
N hours ahead of current time
"""
current = datetime.datetime.utcnow()
if hours:
if isinstance(hours,int):
current = current - datetime.timedelta(hours=hours)
elif isinstance(hours,str):
current = current - datetime.timedelta(hours=int(hours))
if time_format:
tm_format = time_format
else:
tm_format = UTC_FORMAT
d1 = current.strftime(tm_format)
return d1
def decorator(func):
def wrapper(times,time_format=None):
if isinstance(times,int):
distance_time = func(times,time_format)
return distance_time
else:
tes = re.search('(\d*)h$',times)
if tes.group():
current = datetime.datetime.utcnow()
current = current - datetime.timedelta(hours=int(tes.group(1)))
if time_format:
tm_format = time_format
else:
tm_format = UTC_FORMAT
return current.strftime(tm_format)
return wrapper
@decorator
def distance_current_time(num,time_format = None):
"""num days from the current time,
Args:
num ([type]): how many days is it from now
time_format: time format ,like:time_format = "%Y-%m-%d"
Returns:
[type]: [description]
"""
if time_format:
tm_format = time_format
else:
tm_format ="%Y-%m-%d"
distance_time = (datetime.datetime.now() -datetime.timedelta(days=-int(num))).strftime(tm_format)
return distance_time
if __name__ == '__main__':
print(current_time(1))
print(distance_current_time(0))
print(distance_current_time('1h'))