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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - Compare string in format HH:MM to time now in python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...