how to format datetime using pd.to_datetime in python

To format a datetime using pd.to_datetime in Python with pandas, you can pass a format parameter to specify the desired format of the datetime string.

Here's an example of how you can do it:

main.py
import pandas as pd

date_string = "2022-08-31"
formatted_date = pd.to_datetime(date_string, format="%Y-%m-%d")

print(formatted_date)
135 chars
7 lines

In this example, we have a date string in the format "2022-08-31". The format parameter "%Y-%m-%d" specifies that the year is represented by %Y, the month by %m, and the day by %d. When we pass this format parameter to pd.to_datetime, it will interpret the date string accordingly and convert it to a Timestamp object representing the formatted datetime.

The output will be:

main.py
Timestamp('2022-08-31 00:00:00')
33 chars
2 lines

You can also format datetime with additional time information, such as hours, minutes, and seconds. Just update the format parameter accordingly.

Hope this helps!

related categories

gistlibby LogSnag