python / cpython

The Python programming language
https://www.python.org
Other
63.12k stars 30.22k forks source link

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

Open ronaldoussoren opened 11 years ago

ronaldoussoren commented 11 years ago
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: ```python assignee = None closed_at = None created_at = labels = ['3.8', 'type-feature', 'library'] title = "datetime.time support for '+' and '-'" updated_at = user = 'https://github.com/ronaldoussoren' ``` bugs.python.org fields: ```python activity = actor = 'martin.panter' assignee = 'none' closed = False closed_date = None closer = None components = ['Library (Lib)'] creation = 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'] ```

    ronaldoussoren commented 11 years ago

    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.

    ericvsmith commented 11 years ago

    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.

    ronaldoussoren commented 11 years ago

    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.

    7401b932-8338-4bf4-801f-1e426cd5b003 commented 11 years ago

    Patch submitted, please review.

    akheron commented 11 years ago

    Added some comments to Rietveld.

    7401b932-8338-4bf4-801f-1e426cd5b003 commented 11 years ago

    New patch adressing the review comments.

    e9019841-d272-40f2-9d0b-b52653df8f69 commented 11 years ago

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

    7401b932-8338-4bf4-801f-1e426cd5b003 commented 11 years ago

    I am adding yet another patch. This time it has

    in addition to the previous

    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.

    7401b932-8338-4bf4-801f-1e426cd5b003 commented 11 years ago

    New patch, removed whitespace change and unnecessary test.

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

    akheron commented 11 years ago

    LGTM.

    44c179a3-5555-4956-9442-3817761e943f commented 11 years ago

    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.

    ronaldoussoren commented 11 years ago

    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.

    akheron commented 11 years ago

    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.

    fa53c3d6-e97b-4089-8725-a7655c5e9dde commented 11 years ago

    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

    abalkin commented 11 years ago

    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.

    abalkin commented 11 years ago

    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.

    abalkin commented 11 years ago

    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 ...
    abalkin commented 11 years ago

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

    abalkin commented 10 years ago

    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".

    csabella commented 5 years ago

    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!

    pganssle commented 5 years ago

    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?

    vadmium commented 5 years ago

    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.

    Kaligule commented 2 years ago

    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?