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 belopolsky, p-ganssle, tim.peters, vstinner
Date 2018-01-09.16:04:50
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1515513890.14.0.467229070634.issue32522@psf.upfronthosting.co.za>
In-reply-to
Content
An alternate possibility here might be to implement either `__round__` or a `round` function in `datetime` (which would basically automatically add this precision functionality to *all* the constructors, not just now). An example implementation:

from datetime import datetime

    class Datetime(datetime):
        def __round__(self, ndigits=None):
            if ndigits is None:
                return self

            dflt_args = {
                'month': 1,
                'day': 1,
                'hour': 0,
                'minute': 0,
                'second': 0,
                'microsecond': 0
            }

            args = list(dflt_args.keys())

            if ndigits not in dflt_args:
                raise ValueError('Unknown rounding component: %s' % ndigits)

            idx = args.index(ndigits)

            return self.replace(**{arg: dflt_args[arg] for arg in args[idx:]})


It's not great that `__round__`'s argument is `ndigits`, though. If we don't want to just add a `round` method to `datetime`, another option might be to implement `__mod__` somehow, so you could do `datetime.now() % timedelta(seconds=1)`, but that seems complicated (and also doesn't let you round to the nearest month).
History
Date User Action Args
2018-01-09 16:04:50p-gansslesetrecipients: + p-ganssle, tim.peters, belopolsky, vstinner
2018-01-09 16:04:50p-gansslesetmessageid: <1515513890.14.0.467229070634.issue32522@psf.upfronthosting.co.za>
2018-01-09 16:04:50p-gansslelinkissue32522 messages
2018-01-09 16:04:50p-gansslecreate