Orkun
Orkun

Reputation: 522

Extract time from datetime object and compare with string time

In python, I have a datetime object in python with that format.

datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')

In other classes, I'm using this object. When i reach this object,i want to extract time from it and compare string time. Like below;

 if "01:15:13" == time_from_datetime_object 

How can I do this?

Upvotes: 0

Views: 706

Answers (3)

deceze
deceze

Reputation: 522626

Use its time method to return a time object, which you can compare to another time object.

from datetime import time

if datetime_object.time() == time(1, 15, 13):
    ...

You may have to be careful with microseconds though, so at some point you might want to do datetime_object = datetime_object.replace(microsecond=0), should your datetime objects contain non-zero microseconds.

Upvotes: 1

Johnny John Boy
Johnny John Boy

Reputation: 3284

You need to use the strftime method:

from datetime import datetime
date_time_str = '2021-01-15 01:15:13'

datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
    print("match")

Upvotes: 2

buran
buran

Reputation: 14273

If you want to compare it as string:

 if "01:15:13" == datetime_object.strftime('%H:%M:%S'):

Upvotes: 1

Related Questions