Home > Enterprise >  How to convert "Day_Name Month Day_No. Time Year" to date format?
How to convert "Day_Name Month Day_No. Time Year" to date format?

Time:07-26

I have a date column in a df with values like Fri Apr 01 16:41:32 0000 2022. I want to convert it into proper date column format 01/04/2022 16:41:32. Where 01 is day and 04 is the month.

Any guidance please?

CodePudding user response:

You can use pandas.to_datetime for getting datetime then with Series.dt.strftime convert to desired format.

import pandas as pd

# example df
df = pd.DataFrame({'date': ['Fri Apr 01 16:41:32  0000 2022' , 
                            'Sat Apr 02 16:41:32  0000 2022']})


df['date'] = pd.to_datetime(df['date']).dt.strftime('%d/%m/%Y %H:%M:%S')
print(df)

                  date
0  01/04/2022 16:41:32
1  02/04/2022 16:41:32

CodePudding user response:

You can use this to get the datetime type.

from dateutil import parser
date=parser.parse("Fri Apr 01 16:41:32  0000 2022")

If you want a specific string format, you can then use strftime()

CodePudding user response:

first create a dictionary from month and the number of month for example for key "apr" value is 04.

Then with regex create a function for extract the name of month, year, time and day and then with the apply method, apply it on all rows and store output in a new column as a tuple.

now you can use from apply method again for create custom column as

datetime.datetime(year= ..., Month=..., ...)
  • Related