[issue32522] Add precision argument to datetime.now

Alexander Belopolsky report at bugs.python.org
Tue Jan 9 14:54:54 EST 2018


Alexander Belopolsky <alexander.belopolsky at gmail.com> added the comment:

> replacing all elements of a datetime below a certain level is a very common idiom

This can be accomplished rather efficiently by truncating a time tuple:

>>> t = datetime.now()
>>> datetime(*t.timetuple()[:6])
datetime.datetime(2018, 1, 9, 14, 47, 12)
>>> datetime(*t.timetuple()[:5])
datetime.datetime(2018, 1, 9, 14, 47)
>>> datetime(*t.timetuple()[:4])
datetime.datetime(2018, 1, 9, 14, 0)
>>> datetime(*t.timetuple()[:3])
datetime.datetime(2018, 1, 9, 0, 0)

if you do this often, you can wrap this in a function


_PARTS = {'seconds': 6, 'minutes': 5, ...}
def truncate_to(t, timespec):
    return datetime(*t.timetuple()[:_PARTS[timespec])

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32522>
_______________________________________


More information about the Python-bugs-list mailing list