inference.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from __future__ import absolute_import
  2. # Copyright (c) 2010-2019 openpyxl
  3. """
  4. Type inference functions
  5. """
  6. import datetime
  7. import re
  8. from openpyxl.styles import numbers
  9. PERCENT_REGEX = re.compile(r'^(?P<number>\-?[0-9]*\.?[0-9]*\s?)\%$')
  10. TIME_REGEX = re.compile(r"""
  11. ^(?: # HH:MM and HH:MM:SS
  12. (?P<hour>[0-1]{0,1}[0-9]{2}):
  13. (?P<minute>[0-5][0-9]):?
  14. (?P<second>[0-5][0-9])?$)
  15. |
  16. ^(?: # MM:SS.
  17. ([0-5][0-9]):
  18. ([0-5][0-9])?\.
  19. (?P<microsecond>\d{1,6}))
  20. """, re.VERBOSE)
  21. NUMBER_REGEX = re.compile(r'^-?([\d]|[\d]+\.[\d]*|\.[\d]+|[1-9][\d]+\.?[\d]*)((E|e)[-+]?[\d]+)?$')
  22. def cast_numeric(value):
  23. """Explicity convert a string to a numeric value"""
  24. if NUMBER_REGEX.match(value):
  25. try:
  26. return int(value)
  27. except ValueError:
  28. return float(value)
  29. def cast_percentage(value):
  30. """Explicitly convert a string to numeric value and format as a
  31. percentage"""
  32. match = PERCENT_REGEX.match(value)
  33. if match:
  34. return float(match.group('number')) / 100
  35. def cast_time(value):
  36. """Explicitly convert a string to a number and format as datetime or
  37. time"""
  38. match = TIME_REGEX.match(value)
  39. if match:
  40. if match.group("microsecond") is not None:
  41. value = value[:12]
  42. pattern = "%M:%S.%f"
  43. #fmt = numbers.FORMAT_DATE_TIME5
  44. elif match.group('second') is None:
  45. #fmt = numbers.FORMAT_DATE_TIME3
  46. pattern = "%H:%M"
  47. else:
  48. pattern = "%H:%M:%S"
  49. #fmt = numbers.FORMAT_DATE_TIME6
  50. value = datetime.datetime.strptime(value, pattern)
  51. return value.time()