Skip to content

Use the fraction with %s in DateTime.strptime - #207

Open
bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-strptime-seconds-sec-fraction
Open

bardrop wants to merge 1 commit into
ruby:masterfrom
bardrop-oss:fix-strptime-seconds-sec-fraction

Conversation

@bardrop

@bardrop bardrop commented Nov 18, 2026

Copy link
Copy Markdown

DateTime.strptime drops the fraction when the seconds come from %s:

DateTime.strptime('1.5', '%s.%N').sec_fraction            # => (0/1), expected (1/2)
DateTime.strptime('981158400 123', '%s %L').sec_fraction  # => (0/1), expected (1/1000)
Time.strptime('1.5', '%s.%N').subsec                      # => (1/2)

Date._strptime parses it fine ({seconds: 1, sec_fraction: (1/2)}), but rt_rewrite_frags turns seconds into jd/hour/min/sec and then overwrites sec_fraction with the fraction of seconds, which is always 0 for %s.

This adds the parsed fraction to the seconds first, with the sign of the seconds, the same rule Time.strptime uses since Bug #10904 (-1.25 is 1969-12-31 23:59:58.75). It only does this when the seconds are an Integer, so %Q (which already carries the milliseconds) behaves as before.

I checked 20,000 random %s.%N values between 1874 and 2065, positive and negative: DateTime.strptime now gives the same time as Time.strptime for all of them (on master all 20,000 differ). The new test fails on master; the full suite passes on Ruby 4.0.9.

One case still differs from what you'd expect, in both classes: -0.5 reads as +0.5, because _strptime returns seconds: 0 and the minus sign is lost there.

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).
@nobu

nobu commented Nov 18, 2026

Copy link
Copy Markdown
Member

You can use Time.strptime instead.

@bardrop

bardrop commented Nov 18, 2026

Copy link
Copy Markdown
Author

Thanks, yes, Time.strptime gives the right value. The problem is that DateTime.strptime('1.5', '%s.%N') quietly gives a wrong one: _strptime already parsed the fraction, and rt_rewrite_frags throws it away. The fix is three lines and only touches the case where seconds is an Integer.

If you would rather leave DateTime as it is, that is fine. Just say so and I will close this.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

⌂ Proxy