Home > Enterprise >  How can I convert format of values as well as data type in DataFrame and format of values in list in
How can I convert format of values as well as data type in DataFrame and format of values in list in

Time:07-19

I have DataFrame in Python Pandas like below (col1 is in string format):

col1
-----
23.11.2020
22/12/2021
04-12-2019
....

Moreover I have list like below:

my_list = ["23.11.2020", "22/12/2021", "04-12-2019", ...]

And I have 2 thing to do:

  1. Convert values in col1 in df to data type "datetime64" and format like "23-11-2020"
  2. Convert values on my_list to format like "23.11.2020"

So as a result I need:

DataFrame like below:

col1
-----
23-11-2020
22-12-2021
04-12-2019
....

List like below:

my_list = ["23.11.2020", "22.12.2021", "04.12.2019", ...]

How can I do that in Python Pandas ?

CodePudding user response:

pd.to_datetime(ser.str.replace(r"[\.\/]", "-", regex=True), format='%d-%m-%Y').dt.strftime('%d-%m-%Y')

pd.to_datetime(pd.Series(my_list).str.replace(r"[\-\/]", ".", regex=True), format='%d.%m.%Y').dt.strftime('%d.%m.%Y').tolist()
  • Related