1

If I have a dataframe with a datetime column, created using pd.to_datetime(column), I can strip the time part of it using df.col_name.dt.date.

But this column now doesn't let me access .dt method. I can't access .dt.weeks etc methods. Can we not strip the time part of a datetime in pandas without losing the .dt method?

eg:

df = pd.DataFrame({'td': ['2012-12-03']})
df['td'] = pd.to_datetime(df['td'])
df['td'][0] # shows first element, which has time along with date
df['td'] = df['td'].dt.date
df['td'][0] # shows first element, which has only date
df['td'].dt # throws error
Pratham
  • 159
  • 1
  • 8
  • On the last line, `dt['td'].dt` or `df['td'].dt` – NYC Coder Jun 24 '20 at 17:26
  • Fr my curiousity, why would you want to use the `dt` accessor again? – Erfan Jun 24 '20 at 17:26
  • `dt.date` results in an object type, not a datetime. Don't overwrite the column with your datetime data. – Trenton McKinney Jun 24 '20 at 17:27
  • @Erfan Because currently I just want to do the conversion so that my matplotlib plots dont label whole of axes using date along with time, while my data is at day level. What I would rather ask is, why do I even need time part when my data is at day level? – Pratham Jun 24 '20 at 17:46
  • @TrentonMcKinney yeah I understand, so is there a way to store only 'Date'? I am from R background, and it had datatypes which stored either date or datetimes, there was a choice. – Pratham Jun 24 '20 at 17:49
  • So the real question is how to plot only date on the x-axis, which is answered in [Plotting dates on the x-axis with Python's matplotlib](https://stackoverflow.com/questions/9627686/plotting-dates-on-the-x-axis-with-pythons-matplotlib) – Trenton McKinney Jun 24 '20 at 17:49
  • Sorry, I disagree. We can rather say real question is 'is there a way to store only date and only datetime data in pandas?' The answers in that question refer to dealing with the problem using matplotlib, I want to know if it is not possible directly in pandas. Because pd.DF.plot() is quite often used by me. – Pratham Jun 24 '20 at 17:55
  • Dataframe.plot uses matplotlib as the backend, so all the formatting calls shown in the duplicate apply. _is there a way to store only date and only datetime data in pandas_ There is only one datetime format and that is `%Y-%m-%d %H:%M:%S` as displayed when using `pd.to_datetime`. If you take elements of a `.dt` column, they are objects. – Trenton McKinney Jun 24 '20 at 19:44

0 Answers0