0

Data from database Print (LC4.issue_d) 1 2014-12-01 00:00:00 2 2014-12-01 00:00:00 3 2014-12-01 00:00:00 4 2014-12-01 00:00:00 5 2014-12-01 00:00:00 ...
235625 2014-01-01 00:00:00 235626 2014-01-01 00:00:00 235627 2014-01-01 00:00:00 235628 2014-01-01 00:00:00 235629 2014-01-01 00:00:00 Name: issue_d, Length: 235629, dtype: object

I am trying to create an array called Month and let it be the month of the issued date; for example, for issue_d of December 1, 2014, it will return 12 to Month for the observation. The code I used:

import datetime as dt
Month = LC4.issue_d.dt.month
print (Month)

I kept getting the AttributeError: Can only use .dt accessor with datetimelike values

I am new to Python, I don't know where I got it wrong.

Thanks in advance!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
MKT HB
  • 1
  • 1
    it means `LC4.issue_d` is *not* of datetime but object as you show. Putting `LC4.issue_d = pd.to_datetime(LC4.issue_d)` before that month accessing attempt perhaps will resolve the issue. Also note that `.dt` is independent of the "datetime" library of pure Python; it's what pandas developers chose to designate datetime accessor. – Mustafa Aydın Sep 05 '22 at 19:27
  • @MustafaAydın I tried 'LC4.issue_d = pd.to_datetime(LC4.issue_d)' , unfortunately it did not work, the error I got was NameError: name 'pd' is not defined. – MKT HB Sep 05 '22 at 19:47
  • I assumed you're working with the library [pandas](https://pandas.pydata.org/) and did `import pandas as pd` – Mustafa Aydın Sep 05 '22 at 19:49
  • Does this answer your question? [How to convert string to datetime format in pandas python?](https://stackoverflow.com/questions/32204631/how-to-convert-string-to-datetime-format-in-pandas-python) – FObersteiner Sep 05 '22 at 19:53
  • @MustafaAydın I entered `import pandas as pd` a few steps before. Do I need to renter it? – MKT HB Sep 05 '22 at 20:00
  • @MKTHB You need to re-run the entire code for it to take effect, yes. – Mustafa Aydın Sep 05 '22 at 20:01
  • @MustafaAydın the code works. A setting with copy warning popped out: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value instead. Do I need to do something about it? – MKT HB Sep 05 '22 at 20:25
  • @MKTHB Yes; the way you defined `LC4` is probably a subset/filtered version of another dataframe like `LC4 = some_frame[...]` or something. This way, it doesn't always guarantee giving back a copy or a view, hence the warning. To get rid of that, and for the better practice, you can do `LC4 = some_frame[...].copy()`, i.e., please append `.copy()` at the end of the line where you define `LC4`; this guarantees a copy. – Mustafa Aydın Sep 05 '22 at 20:34
  • glad to be of help! – Mustafa Aydın Sep 05 '22 at 21:31

0 Answers0