Vishal
Vishal

Reputation: 20627

Stripping off the seconds in datetime python

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?

Upvotes: 79

Views: 94940

Answers (5)

blaqICE
blaqICE

Reputation: 49

dt = datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
dt = f'{dt.date().__str__()} {dt.time().__str__()[:5]}'

Upvotes: 1

HelloSam
HelloSam

Reputation: 2365

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.

Upvotes: 3

user1981924
user1981924

Reputation: 846

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

Upvotes: 33

ʇsәɹoɈ
ʇsәɹoɈ

Reputation: 23509

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

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

Upvotes: 157

Joseph Spiros
Joseph Spiros

Reputation: 1304

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)

Upvotes: 15

Related Questions