Paul Ganssle <p.gans...@gmail.com> added the comment:

> Looking at the dateutil, I don't see a truncate to rrule function.  Maybe a 
> good starting point would be to implement that in dateutil and if some 
> simpler pattern emerges that can be proposed for stdlib, we can discuss it 
> then.

I think that a "truncate to rrule" function is *way* beyond the scope of the 
standard library, since it would require an actual rrule implementation - about 
which there are still many questions. That said, to accomplish what you want, 
you would just use `rrule.before` (floor) or `rrule.after` (ceil):

    from dateutil.rrule import rrule, DAILY
    from datetime import datetime

    rr = rrule(freq=DAILY, byhour=15, byminute=30, dtstart=datetime(2000, 1, 1))

    print(rr.before(datetime(2011, 4, 17, 12, 18)))
    # 2011-04-16 15:30:00

    print(rr.before(datetime(2011, 4, 17, 16, 17)))
    # 2011-04-17 15:30:00


That said, I don't see why this is any different from the `timespec` option to 
isoformat (with the exception that this would support `day` and `month`). In 
fact, in Python 3.7, you can implement it in *terms* of timespec fairly easily:

    def truncate(dt, timespec):
        return dt.fromisoformat(dt.isoformat(timespec=timespec))

I think the fact that `timespec` is useful indicates why this is useful even 
before serialization - a lot of times you want a datetime *up to a specific 
precision*. I would also argue that the fact that `replace` allows you to 
manipulate each component individually - and the fact that replacing all 
elements of a datetime below a certain level is a very common idiom - 
demonstrates that these arbitrary truncation rulesets *are* special in that 
they are among the most common operations that people do.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue32522>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to