Last active
August 29, 2015 13:56
-
-
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.
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
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