Skip to content

Support for negative timedeltas #23

Open

Description

@Serfentum

Hi! Thank you for your library, I just wanna know is it likely that you will add support for negative deltas? For example

timeparse('-1 days -00:00:14.513431')

gives None, why it would be nice (at least for my purpose) to get negative number of seconds in this delta. Probably also output should be the same for such input

timeparse('-1 days 00:00:14.513431')

It's not crucial and could be circumvented of course, but would be nice to have it from the box, thank you)

Activity

  1. SGmuwa commented on Apr 18, 2021

    @SGmuwa
    from pytimeparse.timeparse import timeparse
    from datetime import timedelta
    
    t = timedelta(days= -1, seconds=5)
    print(t) # -1 day, 0:00:05
    t = timedelta(seconds=timeparse(str(t)))
    print(t) # -2 days, 23:59:55
    t = timedelta(seconds=timeparse(str(t)))
    print(t) # -3 days, 0:00:05
    
    t = timedelta(days= -1, seconds=-5)
    print(t) # -2 days, 23:59:55
    t = timedelta(seconds=timeparse(str(t)))
    print(t) # -3 days, 0:00:05
    t = timedelta(seconds=timeparse(str(t)))
    print(t) # -4 days, 23:59:55
  2. Yuren0312 commented on Oct 18, 2026

    @Yuren0312

    Thanks for the report! I can confirm this on current master: timeparse extracts the leading - and negates the whole field sum, but timedelta.__str__ negates only the day count while the clock stays non-negative. So str(timedelta(days=-1, seconds=5)) = -1 day, 0:00:05 parses as -86405 instead of -86395, and every round-trip drifts further (the repro in the thread: -86405 -> -259195 -> -259205 -> ...).

    I've opened #41 with a minimal fix: the second-count computation was factored into a _sum_fields(mdict, sign) helper, and for the day+clock form a leading minus now negates only the week/day portion while the clock stays positive, matching timedelta semantics. The DAYCLOCK (DD-HH:MM:SS) and unit forms keep their existing whole-expression sign behaviour.

    Now -1 day, 0:00:05 -> -86395 and the round-trip is stable. Two regression tests were added and the two old expectations that encoded the previous (incorrect) whole-expression negation were updated. Verification: python -m unittest discover -s pytimeparse/tests -> 62 tests, OK.

    Happy to adjust if you'd prefer a different approach.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions