Skip to content

Instantly share code, notes, and snippets.

@Dakta
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dakta/9282719 to your computer and use it in GitHub Desktop.
Save Dakta/9282719 to your computer and use it in GitHub Desktop.
A couple useful functions for dealing with python timedelta and human readable representations.
def str_to_timedelta(time_str):
"""Parses a human readable time duration string into a datetime.timedelta object
Order from largest to smallest units. Numeric representation of values. Spaces
optional. Specify units with first letter or full word (plural optional).
Parses weeks, days, hours, minutes, seconds.
Examples:
-"1d5h42m33s"
-"1 day 1 hours 43 seconds" (note that hour or hours is accepted here)
-"8 minutes"
-"8 weeks"
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\d+)\s*(%s((%s)?s?))\s*)?" % (k, k[0], k[1:-1]) for k in keys])
kwargs = {}
for k,v in re.match(regex, time_str).groupdict(default="0").items():
kwargs[k] = int(v)
return timedelta(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment