User 19826
User 19826

Reputation: 599

Python date time field

See this program:

dfPeople = pd.DataFrame({'name': ['alice','bob'],'date_of_birth': ['10/25/1995 03:30','10/29/2002 9:25']})

dfPeople['date_of_birth'] = pd.to_datetime(dfPeople['date_of_birth'])

dfPeople['date_of_birth'].dtype 

theDate = dfPeople['date_of_birth'].dt.date

theDate is supposed to extract the date. When I try something like this

if theDate[0]=='1995-10-25':
    print("equal")

I do not see the statement printed. Thank you in advance.

Upvotes: 1

Views: 61

Answers (1)

jezrael
jezrael

Reputation: 863531

It is expected, because compare type date with type string.

So need:

from datetime import datetime

if theDate[0]==datetime.strptime('1995-10-25', '%Y-%m-%d').date():
     print("equal")

If want compare in pandas for mask is possible use Series.dt.floor or Series.dt.normalize for remove times, but still datetimes, so compare with strings working:

theDate = dfPeople['date_of_birth'].dt.floor('d')
#alternative
#theDate = dfPeople['date_of_birth'].dt.normalize()
print (theDate == '1995-10-25')   
0     True
1    False
Name: date_of_birth, dtype: bool

Upvotes: 4

Related Questions