Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 434
andgeo Avatar asked Mar 06 '14 10:03

andgeo


People also ask

How do I compare time in a string in Python?

Use datetime. strptime() to Calculate Time Difference Between Two Time Strings in Python. The datatime class provides a user with a number of functions to deal with dates and times in Python. The strptime() function is used to parse a string value to represent time based on a given format.

How do you compare time strings?

Use string comparison to compare two time strings, that are formatted as hh:mm:ss , e.g. if (time1 > time2) {} . The the time strings are formatted as hh:mm:ss and are based on a 24 hour clock, the default behavior for string comparison is sufficient.

Can you compare timestamps Python?

Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator. Given time can be converted to pandas timestamp using pandas. Timestamp() method.


1 Answers

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.

like image 192
Paulo Bu Avatar answered Oct 06 '22 03:10

Paulo Bu