在这里,它被转换成一个程序:import re, datetime
def get_seconds(text):
splitted_input = filter(None, re.split('[, ]', text))
assert len(splitted_input) % 2 == 0
grouped_input = zip(*(iter(splitted_input),) * 2)
# ⬆︎ This is tricky; see https://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n
kwargs = {
'year':0,
'month':0,
'day':0,
'hour':0,
'minute':0,
'second':0,
'microsecond':0,
}
for n, unit in grouped_input:
n = int(n)
if unit.startswith('y'):
kwargs['year'] += n
elif unit.startswith('mo'):
kwargs['month'] += n
elif unit.startswith('w'):
kwargs['day'] += 7*n
elif unit.startswith('d'):
kwargs['day'] += n
elif unit.startswith('h'):
kwargs['hour'] += n
elif unit.startswith('m'):
kwargs['minute'] += n
elif unit.startswith('s'):
kwargs['second'] += n
else:
assert False, unit
for k, v in kwargs:
kwargs[k] += getattr(now, k)
now = datetime.datetime.now()
return (datetime.datetime(**kwargs) - now).total_seconds()
本文介绍了一段Python代码,该代码能够将包含多种时间单位(如年、月、周等)的文本字符串解析并转换为对应的总秒数。通过正则表达式处理输入,并使用datetime模块计算从当前时间到指定时间的总秒数。
8万+

被折叠的 条评论
为什么被折叠?



