我在dateutil.relativedelta()
- 元组中使用time_unit
命名了与age
相对应的参数,以及获得相对时间的代码:
def time_delta(age):
now = datetime.fromtimestamp(int(time.time()))
if age.time_unit == "seconds":
relative_time = now - relativedelta(seconds=int(age.value))
elif age.time_unit == "minutes":
relative_time = now - relativedelta(minutes=int(age.value))
elif age.time_unit == "hours":
relative_time = now - relativedelta(hours=int(age.value))
elif age.time_unit == "days":
relative_time = now - relativedelta(days=int(age.value))
elif age.time_unit == "weeks":
relative_time = now - relativedelta(weeks=int(age.value))
elif age.time_unit == "months":
relative_time = now - relativedelta(months=int(age.value))
elif age.time_unit == "years":
relative_time = now - relativedelta(years=int(age.value))
在Python 2.7中是否有任何方法可以使用以下内容:
relative_time = now - relativedelta(eval("eval('age.time_unit') +'=' +age.value"))
以上不起作用。我是否坚持使用if/elif
或者我能做些什么更好的事情?
答案 0 :(得分:5)
$('#test').trigger('click');
(代码未经过测试,但应该可以使用)
答案 1 :(得分:0)
def time_delta(age):
now = datetime.fromtimestamp(int(time.time()))
if age.time_unit in ["seconds","minutes","hours","days","weeks","months","years"]:
exec("relative_time = now - relativedelta({}=int(age.value))".format(age.time_unit))
我知道,我知道。 exec
!!!伙计们,这种模式很安全。
编辑:错字。 exec
,而非eval