Home > front end >  How to creat one type of datetime DF format in excel
How to creat one type of datetime DF format in excel

Time:05-18

I have 5/7/2022 12:57(m/d/yyy)

5/7/2022 13:00 PM(m/d/yyy) time formats.

There are two types of time formats in a column of excel file which I have downloaded.
I want to convert it to '%Y-%m-%d %H:%M:%S'. (The column is in string format).

CodePudding user response:

I guess you have your file loaded from excel to dataframe.

df['date_col'] =  pd.to_datetime(df['date_col'], format='%Y-%m-%d %H:%M:%S')

CodePudding user response:

from dateutil.parser import parse
datestring = "5/7/2022 12:57"
dt = parse(datestring)
print(dt.strftime('%Y-%m-%d %H:%M:%S')) #2022-05-07 12:57:00

CodePudding user response:

You can turn string input to datetime by doing this:

from datetime import datetime

example1 = "5/7/2022 12:57"
example2 = "5/7/2022 13:00 PM"

datetime_object1 = datetime.strptime(example1, "%m/%d/%Y %H:%M")
datetime_object2 = datetime.strptime(example2, "%m/%d/%Y %H:%M %p")

and then you can represent the datetime variable with a string:

formatted_datetime1 = datetime_object1.strftime("%Y-%m-%d, %H:%M:%S")
formatted_datetime2 = datetime_object1.strftime("%Y-%m-%d, %H:%M:%S")

CodePudding user response:

You can try using pandas.Series.dt.strftime method, that will allow you to convert a field into the specified date_format, in this case %Y-%m-%d %H:%M:%S.

df['Column'] = df['Column'].dt.strftime('%Y-%m-%d %H:%M:%S')
  • Related