Python 将字符串转换为 datetime.time 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14295673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string into datetime.time object
提问by Zed
Given the stringin this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes.
鉴于string在这种格式"HH:MM"中,例如"03:55",一个表示3小时55分钟。
I want to convert it to datetime.timeobject for easier manipulation. What would be the easiest way to do that?
我想将它转换为datetime.time对象以便于操作。最简单的方法是什么?
采纳答案by Martijn Pieters
Use datetime.datetime.strptime()and call .time()on the result:
使用datetime.datetime.strptime()并调用.time()结果:
>>> datetime.datetime.strptime('03:55', '%H:%M').time()
datetime.time(3, 55)
The first argument to .strptime()is the string to parse, the second is the expected format.
第一个参数.strptime()是要解析的字符串,第二个参数是预期的格式。
回答by Andreas Jung
>>> datetime.time(*map(int, '03:55'.split(':')))
datetime.time(3, 55)

