将格式HH:MM中的字符串与python中的时间进行比较 [英] Compare string in format HH:MM to time now in python

查看:96
本文介绍了将格式HH:MM中的字符串与python中的时间进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为HH:MM的字符串,需要与Python进行比较。



我读过datetime文档,不了解一个优雅的表现我的比较(总菜鸟也没有帮助:))



感谢您阅读!

解决方案

您可以使用 datetimes strptime() 函数转换字符串到有效的 datetime

 >>> d = datetime.datetime.strptime('15:30','%H:%M')

稍后将它与现在比较 time()

 >>> dnow = datetime.datetime.now()#11:42 am here;)
>> dnow.time()< ; d.time()
True

您还可以阅读doc的 strftime()和strptime()行为解释了这些方法,并有一个很好的表恢复指令来解析日期。


I have a string of the format "HH:MM" and need to compare it to the time now in Python.

I did read through the datetime documentation but could not figure out an elegant to perform my comparison (being a total rookie does not help either:))

Thanks for reading this!

解决方案

You can use datetimes's strptime() function to convert the string to a valid datetime:

>>>d=datetime.datetime.strptime('15:30','%H:%M')

and later compare it to now's time():

>>>dnow=datetime.datetime.now()  #11:42 am here ;)
>>>dnow.time() < d.time()
True

You can read also doc's strftime() and strptime() Behavior which explained these methods and have a very good table resuming the directives to parse dates.

这篇关于将格式HH:MM中的字符串与python中的时间进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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