How to Change String to Date and Time in Pandas

We can use pd.to_datetime() to change from string to datetime format in Pandas Python. The following shows steps of how to do so.

Step 1: Generate sample dataframe

# Generate string datetime
dt_1={"datetime": ["26-03-2022  2:16:00 PM","25-03-2022  2:14:28 PM","27-03-2022  2:17:50 PM"]}
dt_1=pd.DataFrame(dt_1)
print(dt_1)

The following is the printout of the dataframe.

                 datetime
0  26-03-2022  2:16:00 PM
1  25-03-2022  2:14:28 PM
2  27-03-2022  2:17:50 PM

Step 2: Change string to data and time in Pandas

The following shows how to change string to datatime data type in Python.

# Change string to datetime
dt_1["datetime"]=pd.to_datetime(dt_1["datetime"])
print(dt_1["datetime"])
0   2022-03-26 14:16:00
1   2022-03-25 14:14:28
2   2022-03-27 14:17:50
Name: datetime, dtype: datetime64[ns]

Step 3: Access date only after the change (optional)

We can access date only part in a datetime in Pandas by using dt.date.

# access date only part
dt_1["datetime"].dt.date
0    2022-03-26
1    2022-03-25
2    2022-03-27
Name: datetime, dtype: object

Step 4: Access time only after the change (optional)

We can access time only part in a datetime in Pandas by using dt.time.

# access time only part
dt_1["datetime"].dt.time
0    14:16:00
1    14:14:28
2    14:17:50
Name: datetime, dtype: object

Further Reading