now() gives开发者_StackOverflow me
datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
How do I get just datetime.datetime(2010, 7, 6, 5, 27, 0, 0)
(the datetime object) where everything after minutes is zero?
dtwithoutseconds = dt.replace(second=0, microsecond=0)
http://docs.python.org/library/datetime.html#datetime.datetime.replace
I know it's quite old question, but I haven't found around any really complete answer so far.
There's no need to create a datetime object first and subsequently manipulate it.
dt = datetime.now().replace(second=0, microsecond=0)
will return the desired object
You can use datetime.replace
to obtain a new datetime object without the seconds and microseconds:
the_time = datetime.now()
the_time = the_time.replace(second=0, microsecond=0)
Some said Python might be adding nanosecond anytime soon, if so the replace(microsecond=0)
method mentioned in the other answers might break.
And thus, I am doing this
datetime.fromisoformat( datetime.now().isoformat(timespec='minutes') )
Maybe it's a little silly and expensive to go through string representation but it gives me a peace of mind.
dt = datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
dt = f'{dt.date().__str__()} {dt.time().__str__()[:5]}'
精彩评论