Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...