AmIA
AmIA

Reputation: 21

Python - convert time to hours and minutes, not seconds

Time1=`1:02:00`

When I try to do this:

Hrs = datetime.datetime.strptime((Time1), "%H:%M")

I recieve the following error:

ValueError: unconverted data remains: :00

Is there any way that I can convert Time1 to just hours and minutes, and 'ignore' the seconds?

Upvotes: 0

Views: 1849

Answers (2)

Ashalynd
Ashalynd

Reputation: 12563

What you are doing is you are reading time value from a formatted string. If a string looks like H:MM:SS then it doesn't make sense to specify a different format. If you want to format the datetime value without seconds, it's possible with strftime:

>>> Time1="1:02:00"
>>> Hrs = datetime.datetime.strptime((Time1), "%H:%M:%S")
>>> print Hrs.strftime("%H:%M")
01:02

Upvotes: 0

Daniel
Daniel

Reputation: 42748

But you have seconds. So you must convert them, but you can replace them with 0:

datetime.datetime.strptime('1:02:30','%H:%M:%S').replace(second=0)

Upvotes: 4

Related Questions