Parse a duration string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation (excluding years and months) and PostgreSQL's day-time interval format.
(value)
| 131 | |
| 132 | |
| 133 | def parse_duration(value): |
| 134 | """Parse a duration string and return a datetime.timedelta. |
| 135 | |
| 136 | The preferred format for durations in Django is '%d %H:%M:%S.%f'. |
| 137 | |
| 138 | Also supports ISO 8601 representation (excluding years and months) and |
| 139 | PostgreSQL's day-time interval format. |
| 140 | """ |
| 141 | match = ( |
| 142 | standard_duration_re.match(value) |
| 143 | or iso8601_duration_re.match(value) |
| 144 | or postgres_interval_re.match(value) |
| 145 | ) |
| 146 | if match: |
| 147 | kw = match.groupdict() |
| 148 | sign = -1 if kw.pop("sign", "+") == "-" else 1 |
| 149 | if kw.get("microseconds"): |
| 150 | kw["microseconds"] = kw["microseconds"].ljust(6, "0") |
| 151 | kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None} |
| 152 | days = datetime.timedelta(kw.pop("days", 0.0) or 0.0) |
| 153 | if match.re == iso8601_duration_re: |
| 154 | days *= sign |
| 155 | return days + sign * datetime.timedelta(**kw) |