Skip to content

Commit 2dcb22f

Browse files
committed
ASCReader: Improve datetime parsing and support double-defined AM/PM cases
1 parent 3f54cca commit 2dcb22f

File tree

1 file changed

+33
-23
lines changed

1 file changed

+33
-23
lines changed

can/io/asc.py

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -116,41 +116,51 @@ def _extract_header(self) -> None:
116116

117117
@staticmethod
118118
def _datetime_to_timestamp(datetime_string: str) -> float:
119-
# ugly locale independent solution
120-
month_map = {
121-
"Jan": 1,
122-
"Feb": 2,
123-
"Mar": 3,
124-
"Apr": 4,
125-
"May": 5,
126-
"Jun": 6,
127-
"Jul": 7,
128-
"Aug": 8,
129-
"Sep": 9,
130-
"Oct": 10,
131-
"Nov": 11,
132-
"Dec": 12,
133-
"Mär": 3,
134-
"Mai": 5,
135-
"Okt": 10,
136-
"Dez": 12,
119+
MONTH_MAP = {
120+
"jan": 1,
121+
"feb": 2,
122+
"mar": 3,
123+
"apr": 4,
124+
"may": 5,
125+
"jun": 6,
126+
"jul": 7,
127+
"aug": 8,
128+
"sep": 9,
129+
"oct": 10,
130+
"nov": 11,
131+
"dec": 12,
132+
"mär": 3,
133+
"mai": 5,
134+
"okt": 10,
135+
"dez": 12,
137136
}
138-
for name, number in month_map.items():
139-
datetime_string = datetime_string.replace(name, str(number).zfill(2))
140137

141-
datetime_formats = (
138+
DATETIME_FORMATS = (
142139
"%m %d %I:%M:%S.%f %p %Y",
143140
"%m %d %I:%M:%S %p %Y",
144141
"%m %d %H:%M:%S.%f %Y",
145142
"%m %d %H:%M:%S %Y",
143+
"%m %d %H:%M:%S.%f %p %Y",
144+
"%m %d %H:%M:%S %p %Y"
146145
)
147-
for format_str in datetime_formats:
146+
147+
datetime_string_parts = datetime_string.split(" ", 1)
148+
month = datetime_string_parts[0].strip().lower()
149+
150+
try:
151+
datetime_string_parts[0] = f"{MONTH_MAP[month]:02d}"
152+
except KeyError:
153+
raise ValueError(f"Unsupported month abbreviation: {month}") from None
154+
datetime_string = " ".join(datetime_string_parts)
155+
156+
157+
for format_str in DATETIME_FORMATS:
148158
try:
149159
return datetime.strptime(datetime_string, format_str).timestamp()
150160
except ValueError:
151161
continue
152162

153-
raise ValueError(f"Incompatible datetime string {datetime_string}")
163+
raise ValueError(f"Unsupported datetime format: '{datetime_string}'")
154164

155165
def _extract_can_id(self, str_can_id: str, msg_kwargs: dict[str, Any]) -> None:
156166
if str_can_id[-1:].lower() == "x":

0 commit comments

Comments
 (0)