0

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).

deeksha
  • 1
  • 3

4 Answers4

0

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')
Phantoms
  • 145
  • 5
0

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')
lemon
  • 14,875
  • 6
  • 18
  • 38
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0
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
uozcan12
  • 404
  • 1
  • 5
  • 13
  • 2
    Answer could be improved by adding description and links to the library functions used, especially the list of formatting codes recognized by strftime() – Sarah Messer May 17 '22 at 13:16
0

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")
Sequery
  • 90
  • 1
  • 11