Skip to content

datetime.time support for '+' and '-' #61469

Open

Description

@ronaldoussoren
BPO 17267
Nosy @ronaldoussoren, @abalkin, @ericvsmith, @bitdancer, @mmaker, @akheron, @vadmium, @jbatista, @pganssle, @csabella
Files
  • issue17267.patch
  • issue17267.patch: patch for time() + timedelta() (C speedups & pure)
  • issue17267-3.4.diff: time_add and time_subtract
  • issue17267-v2.patch
  • issue17267-v3.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = None
    created_at = <Date 2013-02-21.12:47:59.278>
    labels = ['3.8', 'type-feature', 'library']
    title = "datetime.time support for '+' and '-'"
    updated_at = <Date 2019-04-14.00:33:03.958>
    user = 'https://github.com/ronaldoussoren'

    bugs.python.org fields:

    activity = <Date 2019-04-14.00:33:03.958>
    actor = 'martin.panter'
    assignee = 'none'
    closed = False
    closed_date = None
    closer = None
    components = ['Library (Lib)']
    creation = <Date 2013-02-21.12:47:59.278>
    creator = 'ronaldoussoren'
    dependencies = []
    files = ['29200', '29205', '29206', '29225', '29251']
    hgrepos = []
    issue_num = 17267
    keywords = ['patch', 'needs review']
    message_count = 22.0
    messages = ['182592', '182594', '182595', '182801', '182807', '182814', '182818', '182902', '183090', '183114', '183132', '183137', '183138', '183347', '190697', '190698', '190699', '190700', '212898', '339999', '340046', '340175']
    nosy_count = 12.0
    nosy_names = ['ronaldoussoren', 'belopolsky', 'eric.smith', 'r.david.murray', 'maker', 'petri.lehtinen', 'francismb', 'martin.panter', 'joar', 'jbatista', 'p-ganssle', 'cheryl.sabella']
    pr_nums = []
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue17267'
    versions = ['Python 3.8']

    Activity

    1. ronaldoussoren commented on Feb 21, 2013

      @ronaldoussoren
      ContributorAuthor

      It would be nice if datetime.time would be possible to add a delta to a datetime.time object, and if datetime.time had a method for returning the current time (just like datetime.date and date time.datetime have 'today' and 'now' methods).

      Rationale for the '+' operator: calculating the wall clock time some time after an time on an unspecified date. The easy solution would be:

         tm = datetime.time(13, 20)
         later = tm + datetime.timedelta(hours=5, minutes=44)

      That's is currently not possible, but requires more complicated code.

      Getting the current time without date information currently requires getting done with 'datetime.datetime.now().time()', a class method of 'datetime.time' would IMHO be nicer. I must admit that I don't have a good suggestion for the name of that method.

    2. added
      stdlib
      type-feature
      on Feb 21, 2013
    3. ericvsmith commented on Feb 21, 2013

      @ericvsmith
      Member

      What would this give:

         tm = datetime.time(13, 20)
         later = tm + datetime.timedelta(hours=47, minutes=44)

      datetime.time(13, 4)? Or raise an exception?

      I've thought about this before, but it's always a problem when going over date boundaries. If you define "+" to be modulo 24 hours, then it's not very useful for cases I've looked at. Every time I've used time by itself, I end up going back to datetime. But I'll admit that might be a shortcoming of mine, not the concept.

    4. ronaldoussoren commented on Feb 21, 2013

      @ronaldoussoren
      ContributorAuthor

      IMHO this would to module 24 arithmetic, just like a normal clock.

      When I do calculations with plain time that is what I want, if the date is also important I use datetime.datetime. That a time value silently truncates when going past midnight is IMHO also the obvious behavior.

      The biggest argument against adding this functionality I could come up with is that this can give wrong answers when daylight savings time transitions happen, which could lead to subtle bugs.

    5. joar commented on Feb 23, 2013

      joarmannequin
      Mannequin

      Patch submitted, please review.

    6. akheron commented on Feb 23, 2013

      @akheron
      Member

      Added some comments to Rietveld.

    7. joar commented on Feb 23, 2013

      joarmannequin
      Mannequin

      New patch adressing the review comments.

    8. thezulk commented on Feb 23, 2013

      thezulkmannequin
      Mannequin

      Well I have also made a patch for this, using the datetime operator code as much as possible.. this is for version 3.4..

    9. joar commented on Feb 24, 2013

      joarmannequin
      Mannequin

      I am adding yet another patch. This time it has

      • TZ-aware tests (datetimetester.TestTimeTZ).
      • C time_subtract method.
      • Pure time.__sub__ method.

      in addition to the previous

      • Tests for time + timedelta
      • C time_add
      • Pure time.__add__

      There's one issue though, and that is that I have not quite figured out TZ-aware cross-TZ time - timedelta i.e.

      time(0, tzinfo=est) - timedelta(hours=1) * 5 == time(0, tzinfo=utc)
      

      fails.

      I have included a failing test for it.

    10. joar commented on Feb 26, 2013

      joarmannequin
      Mannequin

      New patch, removed whitespace change and unnecessary test.

      add_time_timedelta arg factor will not be changed, in order to preserve uniformity.

    11. akheron commented on Feb 27, 2013

      @akheron
      Member

      LGTM.

    12. jbatista commented on Feb 27, 2013

      jbatistamannequin
      Mannequin

      IMHO this should be "safe" when the timezone is UTC for example, where there is no problems with daylight savings. What should be the behavior when adding a certain timedelta() and it crosses a date where there is an hour switch due to daylight savings? The unadvised would get incorrect results.

    13. ronaldoussoren commented on Feb 27, 2013

      @ronaldoussoren
      ContributorAuthor

      datetime.time arithmetic cannot be timezone aware, as there is no associated date and hence you cannot possibly know if there it a DST transition.

      I don't think this is a problem. Adding/removing time to a clock value has clear real-world semantics. Using the (naive) real world semantics is the best we can do and should generally give the expected answer.

      As to cross-timezone comparisons:

      time(0, tzinfo=est) - timedelta(hours=1) * 5 == time(0, tzinfo=utc)

      fails because the LHS of '==' is a time in a different timezone than the value on the RHS. That's expected and correct.

    14. akheron commented on Feb 27, 2013

      @akheron
      Member

      A time object isn't associated with any date, so I don't really see a
      problem here. The fact that you can shoot yourself in the leg can be
      documented, noting that you should use datetime instead.

      ISTM the reason why time objects even have an associated timezone is
      to support easy calculations between times in different timezones.

    15. francismb commented on Mar 2, 2013

      francismbmannequin
      Mannequin

      Hi Joar,
      just a detail: is there a reason for the asymmetric check for timedelta isinstance (and raising NotImplemented)? And BTW. isn't a double check for the __sub__ case (or have I missed something)?

      + def __add__(self, other):
      + "Add a time and a timedelta"
      + if not isinstance(other, timedelta):
      + return NotImplemented

      vs.
      …
      + def __sub__(self, other):
      + "Subtract a time and a timedelta."
      + if isinstance(other, timedelta):
      + return self + -other
      + return NotImplemented

      regards,
      francis

    16. abalkin commented on Jun 5, 2013

      @abalkin
      Member

      I left a few minor comments on rietveld for the last patch. I did not see code for time.now() and I don't think adding now() should be combined with time +/- timedelta patch. Let's do one thing at a time.

      I think time + timedelta addition is fairly uncontroversial. In the past, I argued against using detached time objects, but it is not really a valid reason for rejecting a good feature.

      On subtraction, if we add time - timedelta -> time, I think users would expect time - time -> timedelta as well. This, however, is ambiguous if we stay with mod 24h arithmetic. The ambiguity can be lifted by requiring days=0 in the result.

    17. abalkin commented on Jun 5, 2013

      @abalkin
      Member

      This was proposed before and rejected in bpo-1118748, but I think current proposal addresses the ambiguity that was sited as a reason for rejection.

    18. abalkin commented on Jun 5, 2013

      @abalkin
      Member

      See also bpo-3250. If we add mod 24h arithmetics, I would like to see something like time.add_with_carry(timedelta) -> (int, time) method. With it, users who need a specific overflow behavior will be able to implement it easily:

      def check_add(t, td):
          carry, result = t.add_with_carry(tf)
          if carry:
              raise ...
    19. abalkin commented on Jun 5, 2013

      @abalkin
      Member

      I am changing the title to focus this issue on arithmetics. Lack of time.now() is adressed in bpo-8902.

    20. changed the title [-]datetime.time support for '+' and 'now'[/-] [+]datetime.time support for '+' and '-'[/+] on Jun 5, 2013
    21. abalkin commented on Mar 7, 2014

      @abalkin
      Member

      I think the timezone related problems are a red herring. Aware datetime +/- timedelta arithmetics is naive - tzinfo is ignored in calculations and copied to the result:

      http://hg.python.org/cpython/file/c83ce2a1841c/Lib/datetime.py#l1711

      The utcoffset only will only come into play if we want to implement time - time -> timedelta, but this problem is already there in time comparisons:

      http://hg.python.org/cpython/file/c83ce2a1841c/Lib/datetime.py#l1091

      It is up to tzinfo subclass implementation writers to handle inability to compute utcoffset without date fields by raising an exception if necessary. It is perfectly fine for time - time to fail with an error coming from .utcoffset().

      I also don't think the fate of bpo-13936 has any bearing on this issue. As long as we are not trying to implement time + time -> time, we are not introducing any new notion of "zero time".

    22. csabella commented on Apr 11, 2019

      @csabella
      Contributor

      It seems that there was interest in this enhancement a few years ago. @joar, would you be able to convert your patch to a GitHub pull request on the master branch? Thanks!

    23. pganssle commented on Apr 12, 2019

      @pganssle
      Member

      I am pretty neutral on this. I don't think it will be terribly difficult to implement or maintain this, and while there are a few possible behaviors, if you think about it for a bit, addition with overflow behavior *does* seem like the natural way to implement it.

      That said, I don't see an amazingly compelling use case for this. It's fairly rare to need to represent abstract times *at all*, and it's even more rare for performing arithmetic on those abstract times to be meaningful. I think the most dangerous aspect of this is that we might make it easier to do something that, for most people, would be the wrong thing to do.

      Does anyone have some examples of real-world use cases for this, so that we're not designing in a vacuum?

    24. vadmium commented on Apr 14, 2019

      @vadmium
      Member

      A real use case that I have had was with a protocol to activate a device with a daily schedule. The protocol takes start and end hours and minutes of the day. To test the device by activating it over the next few minutes, my ideal way would have taken the current time (according to the device controller) as a “time” object, and added a couple of minutes using “timedelta”. In the end I think I made my protocol API accept both “time” and “timedelta" objects, because I found “timedelta” more flexible for calculations, but the “time” class more natural in other cases.

      The start and end times are local times, and daylight saving could come into play, but in reality I won’t be testing the device at 3 a.m. on a Sunday morning. If I did care, I would have to add my own logic with knowledge of the date and daylight saving, to raise an exception.

      I agree with Alexander about supporting the difference between two “time” instances. The result should be a non-negative “timedelta”, at least zero, and strictly less than 24 h.

    25. transferred this issue fromon Apr 10, 2022
    26. Kaligule commented on Apr 28, 2022

      @Kaligule

      I would like to see this. It is strange that you can have an aware time-object and get the utcoffset as a timedelta, but then you can't adjust the object by that timedelta.

      Converting ("normalizing") a timestamp to UTC should be easy. With this feature it would be easy:

      def convert_time_to_utc(time_of_day):
          return ( time_of_day - time_of_day.utcoffset() ).replace(tzinfo=timezone.utc)

      Is there something I can do to help this get merged?

    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

      3.8 (EOL)stdlibtype-feature

      Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions