AttributeError: Can only use .dt accessor with datetimelike values
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
So you need to find out what is wrong with those specific row values.
See the docs
AttributeError: Can only use .dt accessor with datetimelike values but cells contain date time
The solution is to add utc=True
as follows:
import pandas as pd
df = pd.read_csv("my_csv_content_below.csv")
df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
df["timestamp"] = df["timestamp"].dt.tz_convert(timezone_for_plot)
error Can only use .dt accessor with datetimelike values
Seems like "Date and Time" is not a column with a datetime format. You could try to transform that column with this before that line:
output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time'])
Can only use .dt accessor with datetimelike values pandas error
Your data may contain different timezones, like this:
key system impl_date
1 madison 2021-01-27T13:16:18.000-0600
2 madison 2021-01-27T13:15:04.000-0600
3 lexington 2021-01-27T13:08:27.000-0600
5 park 2021-01-27T13:05:42.000-0500 # here
Option is to pass utc=True
to to_datetime
:
pd.to_datetime(df['impl_date'], errors='coerce', utc=True).dt.strftime('%Y-%m-%d')
And you get:
0 2021-01-27
1 2021-01-27
2 2021-01-27
3 2021-01-27
Name: impl_date, dtype: object
Can only use .dt accessor with datetimelike values
Use format '%Y-%m-%d'
and use .dt.strftime("%Y%m")
Ex:
import pandas as pd
testdata['prd_exp_dt'] = pd.to_datetime(testdata['prd_exp_dt'] ,errors = 'coerce',format = '%Y-%m-%d').dt.strftime("%Y%m")
Attribute error: json file processing .dt accessor with datetimelike values
>>> df
plant_date
0 NaN
1 2021-11-12
>>> df.loc[1, 'plant_date'] = pd.to_datetime(df.loc[1, 'plant_date'], errors='coerce', format='%Y-%m-%d')
>>> df
plant_date
0 NaN
1 2021-11-12 00:00:00
Due to how you're creating your dataframe - it being prepopulated with np.nan
and converting individial "rows" to datetime - the "type" of the column will be object
(because nan
is of type float - so the column contains "mixed types")
>>> df.dtypes
plant_date object
--------------^^^^^^
dtype: object
>>> df['plant_date'].dt
AttributeError: Can only use .dt accessor with datetimelike values
In order to use .dt
you need the column to be of type datetime
>>> df
plant_date
0 NaN
1 2021-11-12
>>> df.dtypes
plant_date object
dtype: object
The simplest way is probably just to call to_datetime()
on the whole column at once - either on out
in your function - or on obs_df
after you create it.
>>> df['plant_date'] = pd.to_datetime(df['plant_date'])
>>> df
plant_date
0 NaT
1 2021-11-12
>>> df.dtypes
plant_date datetime64[ns]
dtype: object
Now you can use .dt
without error
>>> df['plant_date'].dt
<pandas.core.indexes.accessors.DatetimeProperties object at 0x1210fe160>
The harv_date
column should have the same issue.
Related Topics
How to Change My Desktop Background with Python
How to Get Exception Message in Python Properly
How to Force/Ensure Class Attributes Are a Specific Type
Activating Anaconda Environment in VScode
Bin Size in Matplotlib (Histogram)
Can't Open Lib 'Odbc Driver 13 for SQL Server'? Sym Linking Issue
How to Check If One Dictionary Is a Subset of Another Larger Dictionary
Sampling Uniformly Distributed Random Points Inside a Spherical Volume
Do You Use the "Global" Statement in Python
Browse Files and Subfolders in Python
Efficient Way to Remove Keys with Empty Strings from a Dict
How to Efficiently Handle European Decimal Separators Using the Pandas Read_CSV Function
Python - Using the Multiply Operator to Create Copies of Objects in Lists