Reputation: 2365
I have a pandas column called 'date'
which has values and type like 2014-07-30 00:00:00 <class 'datetime.datetime'>
.
I want to remove the time from the date.The end result being `2014-07-30' in datetime.datetime format.
I tried a bunch of solutions like-
df['PSG Date '] = df['PSG Date '].dt.date
but its giving me error-
AttributeError: Can only use .dt accessor with datetimelike values
Upvotes: 5
Views: 12516
Reputation: 164673
First, you should begin with a datetime
series; if you don't have one, use pd.to_datetime
to force this conversion. This will permit vectorised computations:
df = pd.DataFrame({'col': ['2014-07-30 12:19:22', '2014-07-30 05:52:05',
'2014-07-30 20:15:00']})
df['col'] = pd.to_datetime(df['col'])
Next, note you cannot remove time from a datetime
series in Pandas. By definition, a datetime
series will include both "date" and "time" components.
You can use pd.Series.dt.floor
or pd.Series.dt.normalize
to reset the time component to 00:00:00
:
df['col_floored'] = df['col'].dt.floor('d')
df['col_normalized'] = df['col'].dt.normalize()
print(df['col_floored'].iloc[0]) # 2014-07-30 00:00:00
print(df['col_normalized'].iloc[0]) # 2014-07-30 00:00:00
You can convert your datetime
series to an object
series, consisting of datetime.date
objects representing dates:
df['col_date'] = df['col'].dt.date
print(df['col_date'].iloc[0]) # 2014-07-30
Since these are not held in a contiguous memory block, operations on df['col_date']
will not be vectorised.
It's useful to check the dtype
for the series we have derived. Notice the one option which "removes" time involves converting your series to object
.
Computations will be non-vectorised with such a series, since it consists of pointers to datetime.date
objects instead of data in a contiguous memory block.
print(df.dtypes)
col datetime64[ns]
col_date object
col_floored datetime64[ns]
col_normalized datetime64[ns]
Upvotes: 4
Reputation: 862641
I believe need first to_datetime
and for date
s use dt.date
:
df['PSG Date '] = pd.to_datetime(df['PSG Date '], errors='coerce').dt.date
If want datetimes with no times use dt.floor
:
df['PSG Date '] = pd.to_datetime(df['PSG Date '], errors='coerce').dt.floor('d')
Upvotes: 2
Reputation: 29081
You can convert a datetime.datetime
to date time.date
by calling the .date()
method of the object. eg
current_datetime = datetime.datetime.now()
date_only = current_datetime.date()
Upvotes: 0