Skip to content

Commit e27017c

Browse files
committed
ENH: add strptime_micr helper which would support optional microseconds ([.%f])
1 parent 4383fea commit e27017c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

heudiconv/tests/test_utils.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
from datetime import datetime
34
import json
45
from json.decoder import JSONDecodeError
56
import os
@@ -21,6 +22,7 @@
2122
remove_prefix,
2223
remove_suffix,
2324
save_json,
25+
strptime_micr,
2426
update_json,
2527
)
2628

@@ -168,6 +170,24 @@ def test_get_datetime() -> None:
168170
)
169171

170172

173+
@pytest.mark.parametrize(
174+
"dt, fmt",
175+
[
176+
("20230310190100", "%Y%m%d%H%M%S"),
177+
("2023-04-02T11:47:09", "%Y-%m-%dT%H:%M:%S"),
178+
],
179+
)
180+
def test_strptime_micr(dt: str, fmt: str) -> None:
181+
target = datetime.strptime(dt, fmt)
182+
assert strptime_micr(dt, fmt) == target
183+
assert strptime_micr(dt, fmt + "[.%f]") == target
184+
assert strptime_micr(dt + ".0", fmt + "[.%f]") == target
185+
assert strptime_micr(dt + ".000000", fmt + "[.%f]") == target
186+
assert strptime_micr(dt + ".1", fmt + "[.%f]") == datetime.strptime(
187+
dt + ".1", fmt + ".%f"
188+
)
189+
190+
171191
def test_remove_suffix() -> None:
172192
"""
173193
Test utils.remove_suffix()

heudiconv/utils.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,27 @@ def get_datetime(date: str, time: str, *, microseconds: bool = True) -> str:
666666
return datetime_str
667667

668668

669+
def strptime_micr(date_string: str, fmt: str) -> datetime:
670+
r"""
671+
Decorate strptime while supporting optional [.%f] in the format at the end
672+
673+
Parameters
674+
----------
675+
date_string: str
676+
Date string to parse
677+
fmt: str
678+
Format string. If it ends with [.%f], we keep it if date_string ends with
679+
'.\d+' regex and not if it does not.
680+
"""
681+
682+
optional_micr = "[.%f]"
683+
if fmt.endswith(optional_micr):
684+
fmt = fmt[: -len(optional_micr)]
685+
if re.search(r"\.\d+$", date_string):
686+
fmt += ".%f"
687+
return datetime.strptime(date_string, fmt)
688+
689+
669690
def remove_suffix(s: str, suf: str) -> str:
670691
"""
671692
Remove suffix from the end of the string

0 commit comments

Comments
 (0)