Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Last active November 25, 2016 10:44
Show Gist options
  • Save Ivlyth/3931cf4f8803e5eeba031cfabef0120f to your computer and use it in GitHub Desktop.
Save Ivlyth/3931cf4f8803e5eeba031cfabef0120f to your computer and use it in GitHub Desktop.
从git commit中提取时间相关信息计算其距离现在的秒数
'''
例子:
1. '*********** - 1 year, 4 months ago - someone do something1' => 1*365*24*60*60 + 4*30*24*60*60
2. '*********** - 3 months, 7days ago - someone do something2' => 3*30*24*60*60 + 7*24*60*60
3. '*********** - 5 hours ago - someone do something3' => 5*60*60
'''
unit_map = {
'years': 365 * 24 * 60 * 60,
'year': 365 * 24 * 60 * 60,
'months': 30 * 24 * 60 * 60,
'month': 30 * 24 * 60 * 60,
'weeks': 7 * 24 * 60 * 60,
'week': 24 * 60 * 60,
'days': 24 * 60 * 60,
'day': 24 * 60 * 60,
'hours': 60 * 60,
'hour': 60 * 60,
'minutes': 60,
'minute': 60,
'seconds': 1,
'second': 1
}
def commit_time_in_seconds(commit):
'''以秒为单位计算一个commit距离现在的时间'''
res = commit.split('-')
if len(res) <= 1: # can not retrieve time, make it order in front
return 0
times_str = res[1]
if not times_str:
return 0
times = [part.strip() for part in times_str.split(',') if part]
if not times:
return 0
pattern = '(?P<count>\d+)\s*(?P<unit>years?|months?|weeks?|days?|hours?|minutes?|seconds?)'
p = re.compile(pattern)
total_seconds = 0
for t in times:
m = p.match(t)
if not m:
continue
count = m.groupdict().get('count', None)
unit = m.groupdict().get('unit', None)
if count is None or unit is None:
continue
total_seconds += int(count) * unit_map.get(unit, 0)
return total_seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment