├── .github └── workflows │ └── python.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── durationpy ├── __init__.py ├── __init__.pyi ├── duration.py └── py.typed ├── setup.cfg ├── setup.py └── test.py /.github/workflows/python.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | python-version: ["3.9", "3.10", "3.11"] 19 | steps: 20 | - uses: actions/checkout@v3 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v3 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Test 26 | run: | 27 | python test.py 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | /dist/ 3 | /build/ 4 | MANIFEST 5 | .python-version 6 | /durationpy.egg-info 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Ilia Choly 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build: clean 2 | python3 setup.py sdist bdist_wheel 3 | 4 | clean: 5 | rm -rf build dist *.egg-info 6 | 7 | publish: build 8 | twine upload dist/* 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # durationpy 2 | 3 | > Module for converting between `datetime.timedelta` and Go's Duration strings. 4 | 5 | ### Install 6 | 7 | ``` sh 8 | $ pip install durationpy 9 | ``` 10 | 11 | 12 | ### Parse 13 | 14 | * `ns` - nanoseconds 15 | * `us` - microseconds 16 | * `ms` - millisecond 17 | * `s` - second 18 | * `m` - minute 19 | * `h` - hour 20 | 21 | ``` py 22 | # parse 23 | td = durationpy.from_str("4h3m2s1ms") 24 | 25 | # format 26 | durationpy.to_str(td) 27 | ``` 28 | 29 | **Note:** nanosecond precision is lost because `datetime.timedelta` uses microsecond resolution. 30 | -------------------------------------------------------------------------------- /durationpy/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | from .duration import to_str, from_str, DurationError 3 | -------------------------------------------------------------------------------- /durationpy/__init__.pyi: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def from_str(duration: str) -> datetime.timedelta: ... 4 | def to_str(delta: datetime.timedelta, extended: bool = ...) -> str: ... 5 | 6 | class DurationError(ValueError): ... 7 | -------------------------------------------------------------------------------- /durationpy/duration.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | import re 4 | import datetime 5 | 6 | _nanosecond_size = 1 7 | _microsecond_size = 1000 * _nanosecond_size 8 | _millisecond_size = 1000 * _microsecond_size 9 | _second_size = 1000 * _millisecond_size 10 | _minute_size = 60 * _second_size 11 | _hour_size = 60 * _minute_size 12 | _day_size = 24 * _hour_size 13 | _week_size = 7 * _day_size 14 | _month_size = 30 * _day_size 15 | _year_size = 365 * _day_size 16 | 17 | units = { 18 | "ns": _nanosecond_size, 19 | "us": _microsecond_size, 20 | "µs": _microsecond_size, 21 | "μs": _microsecond_size, 22 | "ms": _millisecond_size, 23 | "s": _second_size, 24 | "m": _minute_size, 25 | "h": _hour_size, 26 | "d": _day_size, 27 | "w": _week_size, 28 | "mm": _month_size, 29 | "y": _year_size, 30 | } 31 | 32 | _duration_re = re.compile(r'([\d\.]+)([a-zµμ]+)') 33 | 34 | 35 | class DurationError(ValueError): 36 | """duration error""" 37 | 38 | 39 | def from_str(duration): 40 | """Parse a duration string to a datetime.timedelta""" 41 | 42 | original = duration 43 | 44 | if duration in ("0", "+0", "-0"): 45 | return datetime.timedelta() 46 | 47 | sign = 1 48 | if duration and duration[0] in '+-': 49 | if duration[0] == '-': 50 | sign = -1 51 | duration = duration[1:] 52 | 53 | matches = list(_duration_re.finditer(duration)) 54 | if not matches: 55 | raise DurationError("Invalid duration {}".format(original)) 56 | if matches[0].start() != 0 or matches[-1].end() != len(duration): 57 | raise DurationError( 58 | 'Extra chars at start or end of duration {}'.format(original)) 59 | 60 | total = 0 61 | for match in matches: 62 | value, unit = match.groups() 63 | if unit not in units: 64 | raise DurationError( 65 | "Unknown unit {} in duration {}".format(unit, original)) 66 | try: 67 | total += float(value) * units[unit] 68 | except Exception: 69 | raise DurationError( 70 | "Invalid value {} in duration {}".format(value, original)) 71 | 72 | microseconds = total / _microsecond_size 73 | return datetime.timedelta(microseconds=sign * microseconds) 74 | 75 | def to_str(delta, extended=False): 76 | """Format a datetime.timedelta to a duration string""" 77 | 78 | total_seconds = delta.total_seconds() 79 | sign = "-" if total_seconds < 0 else "" 80 | nanoseconds = round(abs(total_seconds * _second_size), 0) 81 | 82 | if abs(total_seconds) < 1: 83 | result_str = _to_str_small(nanoseconds, extended) 84 | else: 85 | result_str = _to_str_large(nanoseconds, extended) 86 | 87 | return "{}{}".format(sign, result_str) 88 | 89 | 90 | def _to_str_small(nanoseconds, extended): 91 | 92 | result_str = "" 93 | 94 | if not nanoseconds: 95 | return "0" 96 | 97 | milliseconds = int(nanoseconds / _millisecond_size) 98 | if milliseconds: 99 | nanoseconds -= _millisecond_size * milliseconds 100 | result_str += "{:g}ms".format(milliseconds) 101 | 102 | microseconds = int(nanoseconds / _microsecond_size) 103 | if microseconds: 104 | nanoseconds -= _microsecond_size * microseconds 105 | result_str += "{:g}us".format(microseconds) 106 | 107 | if nanoseconds: 108 | result_str += "{:g}ns".format(nanoseconds) 109 | 110 | return result_str 111 | 112 | 113 | def _to_str_large(nanoseconds, extended): 114 | 115 | result_str = "" 116 | 117 | if extended: 118 | 119 | years = int(nanoseconds / _year_size) 120 | if years: 121 | nanoseconds -= _year_size * years 122 | result_str += "{:g}y".format(years) 123 | 124 | months = int(nanoseconds / _month_size) 125 | if months: 126 | nanoseconds -= _month_size * months 127 | result_str += "{:g}mm".format(months) 128 | 129 | days = int(nanoseconds / _day_size) 130 | if days: 131 | nanoseconds -= _day_size * days 132 | result_str += "{:g}d".format(days) 133 | 134 | hours = int(nanoseconds / _hour_size) 135 | if hours: 136 | nanoseconds -= _hour_size * hours 137 | result_str += "{:g}h".format(hours) 138 | 139 | minutes = int(nanoseconds / _minute_size) 140 | if minutes: 141 | nanoseconds -= _minute_size * minutes 142 | result_str += "{:g}m".format(minutes) 143 | 144 | seconds = float(nanoseconds) / float(_second_size) 145 | if seconds: 146 | nanoseconds -= _second_size * seconds 147 | result_str += "{:g}s".format(seconds) 148 | 149 | return result_str 150 | -------------------------------------------------------------------------------- /durationpy/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icholy/durationpy/354a6781a153daa6f2c2ec373ef50b8d8ac2ec20/durationpy/py.typed -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name = 'durationpy', 5 | description = 'Module for converting between datetime.timedelta and Go\'s Duration strings.', 6 | url = 'https://github.com/icholy/durationpy', 7 | author = 'Ilia Choly', 8 | author_email = 'ilia.choly@gmail.com', 9 | download_url = 'https://github.com/icholy/durationpy/tarball/0.10', 10 | version = '0.10', 11 | packages = ['durationpy'], 12 | package_data = {'durationpy': ['py.typed', '*.pyi']}, 13 | license = 'MIT' 14 | ) 15 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | import durationpy 4 | from datetime import timedelta 5 | 6 | millisecond = 1 7 | second = 1000 * millisecond 8 | minute = 60 * second 9 | hour = 60 * minute 10 | day = 24 * hour 11 | week = 7 * day 12 | month = 30 * day 13 | year = 365 * day 14 | 15 | cases = [ 16 | 17 | # simple 18 | ["0", True, 0], 19 | ["5s", True, 5 * second], 20 | ["30s", True, 30 * second], 21 | ["1478s", True, 1478 * second], 22 | 23 | # sign 24 | ["-5s", True, -5 * second], 25 | ["+5s", True, 5 * second], 26 | ["-0", True, 0], 27 | ["+0", True, 0], 28 | 29 | # decimal 30 | ["5.0s", True, 5 * second], 31 | ["5.6s", True, 5*second + 600*millisecond], 32 | ["5.s", True, 5 * second], 33 | [".5s", True, 500 * millisecond], 34 | ["1.0s", True, 1 * second], 35 | ["1.00s", True, 1 * second], 36 | ["1.004s", True, 1*second + 4*millisecond], 37 | ["1.0040s", True, 1*second + 4*millisecond], 38 | ["100.00100s", True, 100*second + 1*millisecond], 39 | 40 | # different units 41 | ["13ms", True, 13 * millisecond], 42 | ["14s", True, 14 * second], 43 | ["15m", True, 15 * minute], 44 | ["16h", True, 16 * hour], 45 | ["11d", True, 11 * day], 46 | ["10w", True, 10 * week], 47 | 48 | # composite durations 49 | ["3h30m", True, 3*hour + 30*minute], 50 | ["10.5s4m", True, 4*minute + 10*second + 500*millisecond], 51 | ["-2m3.4s", True, -(2*minute + 3*second + 400*millisecond)], 52 | ["1h2m3s4ms", True, 1*hour + 2*minute + 3*second + 4*millisecond], 53 | ["10w5d39h9m14.425s", True, 10*week + 5*day + 39*hour + 9*minute + 14*second + 425*millisecond], 54 | 55 | # large value 56 | ["52763797000ms", True, 52763797000 * millisecond], 57 | 58 | # small value 59 | # Use multiplication to preserve rounding errors 60 | ["492us", True, timedelta(microseconds=492).total_seconds() * 1000], 61 | 62 | # errors 63 | ["", False, 0], 64 | ["3", False, 0], 65 | ["-", False, 0], 66 | ["s", False, 0], 67 | [".", False, 0], 68 | ["-.", False, 0], 69 | [".s", False, 0], 70 | ["+.s", False, 0], 71 | ["X3h", False, 0], 72 | ["3hY", False, 0], 73 | ["X72h3m0.5msY", False, 0], 74 | ["+X3h", False, 0], 75 | ["-X3h", False, 0], 76 | 77 | # extended 78 | ["5y2mm", True, 5*year + 2*month], 79 | ["7d", True, 7*day], 80 | ["1y4w1h", True, 1*year + 4*week + 1*hour], 81 | ["-7d", True, -7*day] 82 | ] 83 | 84 | class DurationTest(unittest.TestCase): 85 | 86 | def test_parser(self): 87 | for [input, passes, expected] in cases: 88 | if passes: 89 | actual = durationpy.from_str(input).total_seconds() * 1000 90 | self.assertEqual( 91 | expected, actual, 92 | "{}, expecting {}, got {}".format(input, expected, actual)) 93 | else: 94 | with self.assertRaises(durationpy.DurationError, msg=repr(input)) as context: 95 | durationpy.from_str(input) 96 | self.assertIn(input, str(context.exception), msg="error did not contain input") 97 | 98 | def test_formatter(self): 99 | for [input, passes, expected] in cases: 100 | if passes: 101 | dt = durationpy.from_str(input) 102 | ds = durationpy.to_str(dt) 103 | actual = durationpy.from_str(ds).total_seconds() * 1000 104 | self.assertEqual( 105 | expected, actual, 106 | "{}, expecting {}, got {}".format(input, expected, actual)) 107 | 108 | if __name__ == '__main__': 109 | unittest.main() 110 | --------------------------------------------------------------------------------