1

originally Date column is a string type without any null value.


import pandas as pd

# Import the dataframe
eq = pd.read_csv('Ch03_Earthquake_database.csv')

# Describe the dataframe
eq.describe()

eq['Date'].dtypes
dtype('O')

use pd.to_datetime() to convert string into datetime, why after using to_datetime(), the data type is still a string instead of datetime? Thanks

eq['Date']=pd.to_datetime(eq['Date'])
eq['Date'].dtypes
dtype('O')

then I also use dt.year to get year value

eq['Date'].dt.year

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-d248f5bb9e47> in <module>
----> 1 eq['Date'].dt.year

~\miniconda3\envs\forecast\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5459             or name in self._accessors
   5460         ):
-> 5461             return object.__getattribute__(self, name)
   5462         else:
   5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):

~\miniconda3\envs\forecast\lib\site-packages\pandas\core\accessor.py in __get__(self, obj, cls)
    178             # we're accessing the attribute of the class, i.e., Dataset.geo
    179             return self._accessor
--> 180         accessor_obj = self._accessor(obj)
    181         # Replace the property with the accessor object. Inspired by:
    182         # https://www.pydanny.com/cached-property.html

~\miniconda3\envs\forecast\lib\site-packages\pandas\core\indexes\accessors.py in __new__(cls, data)
    492             return PeriodProperties(data, orig)
    493 
--> 494         raise AttributeError("Can only use .dt accessor with datetimelike values")

AttributeError: Can only use .dt accessor with datetimelike values

roudan
  • 3,082
  • 5
  • 31
  • 72
  • 1
    A sample DataFrame that reproduces this behaviour would really help. – Henry Ecker Oct 21 '21 at 00:53
  • Thanks how to upload csv file? – roudan Oct 21 '21 at 00:56
  • Just copy and paste a few rows [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888). or even better make a sample dataframe `eq = pd.DataFrame(...)` and copy it as code. – Henry Ecker Oct 21 '21 at 00:57
  • 1
    [This question](https://stackoverflow.com/questions/58326801/pd-to-datetime-returns-an-object-not-a-time-series/58327579#58327579) might be helpful to you. – Quang Hoang Oct 21 '21 at 01:14
  • Yes Thank you Quang. It works after adding UTC=True as shown below. Now the question is how does it know if it is UTC or not. The date data is just a regular string like 01/02/1965. eq['Date']=pd.to_datetime(eq['Date'],utc=True) eq['Date'].dtypes datetime64[ns, UTC – roudan Oct 21 '21 at 02:04
  • 2
    If that works, then somewhere in you data, there's a date with timezone information... – Quang Hoang Oct 21 '21 at 02:26
  • Thank you so much Quang! – roudan Oct 21 '21 at 02:28

0 Answers0