This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author p-ganssle
Recipients barry, belopolsky, p-ganssle, tim.peters, vstinner
Date 2018-01-09.19:24:22
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1515525862.99.0.467229070634.issue32522@psf.upfronthosting.co.za>
In-reply-to
Content
> 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.
History
Date User Action Args
2018-01-09 19:24:23p-gansslesetrecipients: + p-ganssle, tim.peters, barry, belopolsky, vstinner
2018-01-09 19:24:22p-gansslesetmessageid: <1515525862.99.0.467229070634.issue32522@psf.upfronthosting.co.za>
2018-01-09 19:24:22p-gansslelinkissue32522 messages
2018-01-09 19:24:22p-gansslecreate