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