简体   繁体   中英

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM