Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare only time part in datetime - Python

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

like image 555
Amit K. Avatar asked Feb 27 '13 05:02

Amit K.


People also ask

How do I extract time from a datetime object in Python?

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.

How do I compare only time in python?

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.

Can we compare datetime in Python?

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.


3 Answers

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() 
like image 115
matt Avatar answered Oct 24 '22 04:10

matt


Compare their times using datetime.time().

like image 24
jarmod Avatar answered Oct 24 '22 02:10

jarmod


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
like image 25
Yueyoum Avatar answered Oct 24 '22 02:10

Yueyoum