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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With