timeparse.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. timeparse.py
  5. (c) Will Roberts <[email protected]> 1 February, 2014
  6. This is a vendored and modified copy of:
  7. github.com/wroberts/pytimeparse @ cc0550d
  8. It has been modified to mimic the behaviour of
  9. https://golang.org/pkg/time/#ParseDuration
  10. '''
  11. # MIT LICENSE
  12. #
  13. # Permission is hereby granted, free of charge, to any person
  14. # obtaining a copy of this software and associated documentation files
  15. # (the "Software"), to deal in the Software without restriction,
  16. # including without limitation the rights to use, copy, modify, merge,
  17. # publish, distribute, sublicense, and/or sell copies of the Software,
  18. # and to permit persons to whom the Software is furnished to do so,
  19. # subject to the following conditions:
  20. #
  21. # The above copyright notice and this permission notice shall be
  22. # included in all copies or substantial portions of the Software.
  23. #
  24. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  28. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  29. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  30. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31. # SOFTWARE.
  32. from __future__ import absolute_import
  33. from __future__ import unicode_literals
  34. import re
  35. HOURS = r'(?P<hours>[\d.]+)h'
  36. MINS = r'(?P<mins>[\d.]+)m'
  37. SECS = r'(?P<secs>[\d.]+)s'
  38. MILLI = r'(?P<milli>[\d.]+)ms'
  39. MICRO = r'(?P<micro>[\d.]+)(?:us|µs)'
  40. NANO = r'(?P<nano>[\d.]+)ns'
  41. def opt(x):
  42. return r'(?:{x})?'.format(x=x)
  43. TIMEFORMAT = r'{HOURS}{MINS}{SECS}{MILLI}{MICRO}{NANO}'.format(
  44. HOURS=opt(HOURS),
  45. MINS=opt(MINS),
  46. SECS=opt(SECS),
  47. MILLI=opt(MILLI),
  48. MICRO=opt(MICRO),
  49. NANO=opt(NANO),
  50. )
  51. MULTIPLIERS = dict([
  52. ('hours', 60 * 60),
  53. ('mins', 60),
  54. ('secs', 1),
  55. ('milli', 1.0 / 1000),
  56. ('micro', 1.0 / 1000.0 / 1000),
  57. ('nano', 1.0 / 1000.0 / 1000.0 / 1000.0),
  58. ])
  59. def timeparse(sval):
  60. """Parse a time expression, returning it as a number of seconds. If
  61. possible, the return value will be an `int`; if this is not
  62. possible, the return will be a `float`. Returns `None` if a time
  63. expression cannot be parsed from the given string.
  64. Arguments:
  65. - `sval`: the string value to parse
  66. >>> timeparse('1m24s')
  67. 84
  68. >>> timeparse('1.2 minutes')
  69. 72
  70. >>> timeparse('1.2 seconds')
  71. 1.2
  72. """
  73. match = re.match(r'\s*' + TIMEFORMAT + r'\s*$', sval, re.I)
  74. if not match or not match.group(0).strip():
  75. return
  76. mdict = match.groupdict()
  77. return sum(
  78. MULTIPLIERS[k] * cast(v) for (k, v) in mdict.items() if v is not None)
  79. def cast(value):
  80. return int(value, 10) if value.isdigit() else float(value)