def cache_with_duration(duration=(60 * 60)): # Default duration is 1 hour import datetime, functools def decorator(func): cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): now = datetime.datetime.now() if args not in cache or (now - cache[args]['time']).total_seconds() > duration: result = func(*args, **kwargs) cache[args] = {'result': result, 'time': now} return cache[args]['result'] return wrapper return decorator @cache_with_duration(duration=3) def cache_with_duration_example(): import datetime now = datetime.datetime.now() return f"Current time is: {now.strftime('%Y-%m-%d %H:%M:%S')}" # this will only update every 3 seconds cache_with_duration_example()