Stripping off the seconds in datetime python

Question:

now() gives 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?

Asked By: Vishal

||

Answers:

dtwithoutseconds = dt.replace(second=0, microsecond=0)

http://docs.python.org/library/datetime.html#datetime.datetime.replace

Answered By: ʇsәɹoɈ

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)
Answered By: Joseph Spiros

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

Answered By: user1981924

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.

Answered By: HelloSam
dt = datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
dt = f'{dt.date().__str__()} {dt.time().__str__()[:5]}'
Answered By: blaqICE
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.