Search code snippets, questions, articles...

String to date conversion using Pandas

If you are using panda library in your python project and want to convert a string to a date object then you can use the to_datetime() function of pandas.
import pandas as pd

result = pd.to_datetime("09-08-2021", format='%m-%d-%Y')

print(result)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

2021-09-08 00:00:00

Pandas to_datetime() function

The to_datetime() function in Python Pandas library can be used to convert a date string to a date object. It takes two parameters one is the date string that you want to convert to the date object and the format of the string.

Basic Syntax

pd.to_datetime(date_string, format=date_format)

Code Example

import pandas as pd

date_str = "07/10/2022"
date_format = "%m/%d/%Y"
result = pd.to_datetime(date_str, format=date_format)

print(result)

Output

2022-07-10 00:00:00
Was this helpful?
0 Comments