0

I have a pandas dataframe with a row

clear_date

2019-11-06 00:00:00

2019-11-06 00:00:00

...

type(clear_date) = object

I want to subtract this column from another date-time column whose type is date-time and format '%Y%m%d'.

pd.to_datetime(data['clear_date']).dt.day

I have tried using the above command but the type of clear_date still remains as object and does not change to time-date object and hence I can't subtract another time-date column with it.

How to change it to date-time object with format '%Y%m%d'.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • `format` is only used to read strings _into_ the `datetime64[ns]/timedelta64[ns]` dtypes or to convert those objects back to strings (perhaps to match some API/DB required format). But once you have the datetime dtype that's it, there's no format and you can just do the math and then if you want format the output after the math. But often it's best to leave it in the datetime types that way you can do further manipulations. – ALollz Jan 23 '21 at 15:42
  • But this answer should help. It has a link to all the formatting strings. https://stackoverflow.com/a/26763793/4333359. The format will need to match **exactly** so since you also have hour:minute:seconds that will need to be added to your format, i.e. `'%Y-%m-%d %H:%M:%S'` – ALollz Jan 23 '21 at 16:14
  • besides the formatting discussion, how do you intend to *subtract* two datetimes from each other? I mean what should the result tell you? To me, this makes no sense; you can add or subtract a *duration* (timedelta dtype) to/from datetime, but not datetime and datetime. – FObersteiner Jan 23 '21 at 16:32

1 Answers1

0
data['clear_date'].astype('datetime64[ns]')

As you require it as an object in the output, the data type of the ‘clear_date’ column is an object i.e. string. Now we will convert it to DateTime format using DataFrame.astype() function.