Created
March 15, 2011 22:52
-
-
Save danielnorberg/871688 to your computer and use it in GitHub Desktop.
This file contains 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
import re | |
from datetime import timedelta | |
def parseTimeDelta(s): | |
"""Create timedelta object representing time delta | |
expressed in a string. | |
""" | |
if s is None: | |
return None | |
d = re.match( | |
r'((?P<days>\d+)\s*(days|day|d)\s*,?)?\s*((?P<hours>\d+)\s*:\s*' | |
r'(?P<minutes>\d+)\s*:\s*(?P<seconds>\d+))?\s*', | |
str(s)).groupdict(0) | |
return timedelta(**dict(( (key, int(value)) | |
for key, value in d.items() ))) | |
def formatTimeDelta(z, defaultValue='', formatSecs=True): | |
if not z: | |
return defaultValue | |
min, sec = divmod(z.seconds, 60) | |
hrs, min = divmod(min, 60) | |
if z.days == 0: | |
days = '' | |
elif z.days == 1: | |
days = '1 day, ' | |
else: | |
days = '%d days, ' % z.days | |
if formatSecs: | |
return days + '%02d:%02d:%02d' % (hrs, min, sec) | |
else: | |
return days + '%02d:%02d' % (hrs, min) | |
if __name__ == '__main__': | |
from datetime import datetime | |
times = ['1d, 5:4:3', | |
'64 days , 18:4:53', | |
'7d', | |
'14 days', | |
'14:45:54', | |
'1233:45:54', | |
'543245:4:6', | |
'1d', | |
] | |
now = datetime.now() | |
for time in times: | |
td = parseTimeDelta(time) | |
td2 = parseTimeDelta(str(td)) | |
print td==td2 | |
print td | |
print td2 | |
print '%s + %s = %s' % (now, td, now + td) | |
print '%s - %s = %s' % (now, td, now - td) | |
print formatTimeDelta(td) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment