From b1d2121902a0d3a2e3a58758d24dad1ead9a3c61 Mon Sep 17 00:00:00 2001 From: Benjamin Bertincourt Date: Sat, 27 Jan 2024 16:03:26 -0500 Subject: [PATCH] support various number of digits after the comma in the timestamp %f format --- parse.py | 2 +- tests/test_parse.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/parse.py b/parse.py index 2e6c2c2..d807f49 100644 --- a/parse.py +++ b/parse.py @@ -307,7 +307,7 @@ def strf_date_convert(x, _, type): "%p": "(?:AM|PM)", "%M": "[0-9]{2}", "%S": "[0-9]{2}", - "%f": "[0-9]{6}", + "%f": "[0-9]{1,6}", "%z": "[+|-][0-9]{2}(:?[0-9]{2})?(:?[0-9]{2})?", # "%Z": punt "%j": "[0-9]{1,3}", diff --git a/tests/test_parse.py b/tests/test_parse.py index 69d35dd..a538c73 100644 --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -375,6 +375,23 @@ def test_flexible_datetime_with_colon(): assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27) +def test_datetime_with_various_subsecond_precision(): + r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.123456") + assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123456) + + r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.12345") + assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123450) + + r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.1234") + assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123400) + + r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.123") + assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 123000) + + r = parse.parse("{dt:%Y-%m-%d %H:%M:%S.%f}", "2023-11-21 13:23:27.0") + assert r.named["dt"] == datetime(2023, 11, 21, 13, 23, 27, 0) + + @pytest.mark.skipif( sys.version_info[0] < 3, reason="Python 3+ required for timezone support" )