0

Please, wait before marking it as a duplicate.
These posts
How to change the datetime format in Pandas
Converting object to datetime format in python
answered my question partially.

Sample data:
date1:
04/26/2012
02/16/2006
11/26/2017
...
dtype: object

I converted an object type to datetime64 like this by following the above-linked post:

df['date1'] = pd.to_datetime(df['date1'], format='%m/%d/%Y')

The code returned results in the format %Y-%m-%d. format='%m/%d/%Y' didn't preserve the original form which was %m/%d/%Y. However, the dtype was changed to datetime64[ns] from object which I wanted.

So, I added another line of code to get the original format based on the answers from the above-linked posts.

df['date1'] = df['date1'].dt.strftime('%m/%d/%Y')

Again, the column's data type was converted back to object. But, I need to retain the datetime64 data type.

How to preserve the original formatting, '%m/%d/%Y' with the dtype: datetime64?

007mrviper
  • 459
  • 4
  • 20
  • Do you need to retain the format whilst working with `datetune64[ns]`? Could you work with the datetime type, then convert to desired format for presenting once you have finished manipulating the data? – Rawson May 27 '23 at 22:26
  • I could work the way you suggested. But, I wanted to know if there are any solutions to the problem. – 007mrviper May 27 '23 at 22:37
  • 4
    `datetime` values do not have a format. They are strictly binary objects that store a date value. The format only comes in to play when a `datetime` column is printed. So, leave your values in binary while you work with the data. When you need to print a report or something, THEN you can specify a format. – Tim Roberts May 28 '23 at 01:22

0 Answers0