How to modify format and form of presenting date column in Python Pandas?

108 views Asked by At

I have Python Pandas DataFrame like below:

col1
----
01.05.2019
02.11.2022
11.08.2001

And col1 is in "object" format.

I need to read this Data Frame from csv and in "read_csv" function modify:

  1. format of this column from "object" to "date"
  2. form of presenting values, because when I use only: df= pd.read_csv("df.csv", delimiter=";", index_col=0, parse_dates=['col1']) format of "col1" is "date" but the form is changed to for example: "2019-05-01"

My code is as below:

df= pd.read_csv("df.csv", delimiter=";", index_col=0, parse_dates=['col1'], date_parser=lambda x: pd.to_datetime(x, format='%d.%m.%Y'))

How can I modify my code based of my needs ?

  1. Currently in cas I have form of
  2. date like: 01.05.2019
  3. Nevertheless, it is "object"
  4. I would like to modify format od column from "object" to "date" and still have values in column "date" in format like: 01.05.2019
  5. Neveerthleess, when I use my code I finally have format of data like "datetime" but form is not good because like: 2019-05-01.
1

There are 1 answers

0
ako On

If this is just a question of formatting the date and not parsing it - you can do as follows:

import io

some_data = """a   01.05.2019
b   02.11.2022
c   11.08.2001"""

# read data, ensuring parsing as datetime64
some_df = pd.read_csv(io.StringIO(some_data), delimiter='\s+', names=['ix', 'date'], parse_dates=[
                      'date'], date_parser=lambda x: pd.to_datetime(x, format='%d.%m.%Y'))


# format the date to a string as desired
some_df['date_formated'] = some_df.date.apply(lambda x: x.strftime('%d.%m.%Y'))
some_df

  ix       date date_formated
0  a 2019-05-01    01.05.2019
1  b 2022-11-02    02.11.2022
2  c 2001-08-11    11.08.2001