I want to compare only time part in datetime. I have different dates with only time field to compare. Since dates are different and only time part i want to consider So i think creating two datetime object will not help. my string as
start="22:00:00"
End="03:00:00"
Tocompare="23:30:00"
Above are strings when i convert them with datetime as
dt=datetime.strptime(start,"%H:%M:%S")
it gives
1900-01-01 22:00:00
which is default date in python.
So i need to avoid all this and want only time part. I simply need to check does my Tocompare
falls between start
and End
How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.
Just call the . time() method of the datetime objects to get their hours, minutes, seconds and microseconds. Show activity on this post. Compare their times using datetime.
When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to.
Just call the .time()
method of the datetime
objects to get their hours, minutes, seconds and microseconds.
dt = datetime.strptime(start,"%H:%M:%S").time()
Compare their times using datetime.time().
import datetime
start = datetime.datetime.strptime(start, '%H:%M:%S')
start = datetime.time(start.hour, start.minute,start.second)
tocompare = datetime.datetime.strptime(tocompare, '%H:%M:%S')
tocompare = datetime.time(tocompare.hour, tocompare.minute, tocompare.second)
start > tocompare # False
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