Stripping off the seconds in datetime python

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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

Solution 3 - Python

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)

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVishalView Question on Stackoverflow
Solution 1 - PythonʇsәɹoɈView Answer on Stackoverflow
Solution 2 - Pythonuser1981924View Answer on Stackoverflow
Solution 3 - PythonJoseph SpirosView Answer on Stackoverflow
Solution 4 - PythonHelloSamView Answer on Stackoverflow