ps0604
ps0604

Reputation: 1071

Comparing pandas to_datetime with datetime object

Why the result below is True? The date objects have different types, how is this comparison done?

import pandas as pd
import datetime
df = pd.DataFrame({
    'year': [2015, 2016, 2019, 2016],
    'month': [2, 3, 8, 9],
    'day': [4, 5, 25, 15]} )
df2 = pd.to_datetime(df)
df2

0 2015-02-04
1 2016-03-05
2 2019-08-25
3 2016-09-15
dtype: datetime64[ns]

date1 = df2.iloc[1]
date1

Timestamp('2016-03-05 00:00:00')

date2 = datetime.datetime(2016, 3, 5)
date2

datetime.datetime(2016, 3, 5, 0, 0)

date1 == date2

True

Upvotes: 0

Views: 175

Answers (2)

Corralien
Corralien

Reputation: 120391

As @not_speshal wrote, the documentation is clear. With the moduleinspect, you can see pandas.Timestamp inherits from datetime.datetime.

>>> inspect.getmro(pd.Timestamp)
(pandas._libs.tslibs.timestamps.Timestamp,
 pandas._libs.tslibs.timestamps._Timestamp,
 pandas._libs.tslibs.base.ABCTimestamp,
 datetime.datetime,
 datetime.date,
 object)

For more details, you can read this two files timestamps.pyi and timestamps.pyx from Pandas repository.

Upvotes: 2

wwnde
wwnde

Reputation: 26676

df2['Date']=pd.to_datetime(df2['Date'])#Coerce df2.Date to datetime assumming df2 is stand alone with own Date field
df['Date']=pd.to_datetime(df.apply(lambda x: x.astype(str).str.cat(sep='-'), axis=1))#Concat df entities to date string and coerce it to datettime
df['Date']==df2['Date']#Compare the two

outcome

0    True
1    True
2    True
3    True

Upvotes: 0

Related Questions