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

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

----------

_______________________________________
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