Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Created April 26, 2018 06:15
Show Gist options
  • Save allenyang79/ed74f0655b5e3e0b9e2a75840d271a5f to your computer and use it in GitHub Desktop.
Save allenyang79/ed74f0655b5e3e0b9e2a75840d271a5f to your computer and use it in GitHub Desktop.
process time period string like 'w', 'd', 'h', 'm' , 's'
from datetime import timedelta
import re
UNITS = {"s":"seconds", "m":"minutes", "h":"hours", "d":"days", "w":"weeks"}
def convert_to_seconds(s):
params = {}
for amount, u in re.findall(r'(?:(\d+)([smhdw])\s*)', s):
u = UNITS[u]
amount = int(amount)
if u in params:
raise Exception('duplicate unit %s' % u)
params[u] = amount
td = timedelta(**params)
return int(td.total_seconds())
print convert_to_seconds('1m30s') # 90
print convert_to_seconds('3m') # 180
print convert_to_seconds('1h') # 10800
print convert_to_seconds('1h18m36s') # 4716
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment