[英]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? 有什么方法可以将
Time1
转换为小时和分钟,并“忽略”秒?
But you have seconds. 但是你有几秒钟。 So you must convert them, but you can replace them with 0:
因此,您必须转换它们,但可以将它们替换为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.
如果字符串看起来像H:MM:SS,则没有必要指定其他格式。 If you want to format the datetime value without seconds, it's possible with strftime:
如果要格式化日期时间值而不用秒,则可以使用strftime:
>>> Time1="1:02:00"
>>> Hrs = datetime.datetime.strptime((Time1), "%H:%M:%S")
>>> print Hrs.strftime("%H:%M")
01:02
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.