Created
April 26, 2018 06:15
-
-
Save allenyang79/ed74f0655b5e3e0b9e2a75840d271a5f to your computer and use it in GitHub Desktop.
process time period string like 'w', 'd', 'h', 'm' , 's'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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