From 362820146f0dac8a34ad8a638b96c23b72eba3f3 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Wed, 18 Nov 2026 11:20:34 +0530 Subject: [PATCH] Use the sec_fraction with %s in DateTime.strptime DateTime.strptime('1.5', '%s.%N') dropped the fraction because rt_rewrite_frags replaced sec_fraction with the fraction of seconds, which is always 0 for %s. Add the parsed fraction to the seconds, with the sign of the seconds as Time.strptime does (Bug #10904). --- ext/date/date_core.c | 10 ++++++++++ test/date/test_date_strptime.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/ext/date/date_core.c b/ext/date/date_core.c index 7353dc8..e163fc9 100644 --- a/ext/date/date_core.c +++ b/ext/date/date_core.c @@ -4098,6 +4098,16 @@ rt_rewrite_frags(VALUE hash) if (!NIL_P(seconds)) { VALUE offset, d, h, min, s, fr; + fr = ref_hash("sec_fraction"); + if (!NIL_P(fr) && RB_INTEGER_TYPE_P(seconds)) { + /* "%s.%N": the fraction has the sign of the seconds, + as in Time.strptime. */ + if (f_negative_p(seconds)) + seconds = f_sub(seconds, fr); + else + seconds = f_add(seconds, fr); + } + offset = ref_hash("offset"); if (!NIL_P(offset)) seconds = f_add(seconds, offset); diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index 23fe71e..0ae9077 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -389,6 +389,32 @@ def test_strptime__minus [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) end + def test_strptime__seconds_with_fraction + d = DateTime.strptime('1.5', '%s.%N') + assert_equal([1970, 1, 1, 0, 0, 1, 1.to_r/2], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) + d = DateTime.strptime('981158400.123456789', '%s.%N') + assert_equal([2001, 2, 3, 0, 0, 0, 123456789.to_r/10**9], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) + d = DateTime.strptime('981158400 123', '%s %L') + assert_equal([2001, 2, 3, 0, 0, 0, 123.to_r/10**3], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) + + # The fraction takes the sign of the seconds, as in Time.strptime. + d = DateTime.strptime('-1.25', '%s.%N') + assert_equal([1969, 12, 31, 23, 59, 58, 3.to_r/4], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) + + d = DateTime.strptime('1.5 +0900', '%s.%N %z') + assert_equal([1970, 1, 1, 9, 0, 1, 1.to_r/2, 9.to_r/24], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction, d.offset]) + + # %Q already holds the fraction. + d = DateTime.strptime('1500 500000000', '%Q %N') + assert_equal([1970, 1, 1, 0, 0, 1, 1.to_r/2], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction]) + end + def test_strptime__comp n = DateTime.now