将字符串转换为 datetime.time 对象 [英] Convert string into datetime.time object

查看:41
本文介绍了将字符串转换为 datetime.time 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这种格式的string"HH:MM",例如"03:55",表示3小时 55 分钟.

我想将其转换为 datetime.time 对象以便于操作.最简单的方法是什么?

解决方案

使用 datetime.datetime.strptime() 并调用 .time() 在结果上:

<预><代码>>>>datetime.datetime.strptime('03:55', '%H:%M').time()日期时间.时间(3, 55)

.strptime() 的第一个参数是要解析的字符串,第二个参数是预期的格式.

Given the string in this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes.

I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that?

解决方案

Use datetime.datetime.strptime() and call .time() on the result:

>>> 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.

这篇关于将字符串转换为 datetime.time 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆