How to convert datetime to strings in python

Question:

I have a dataframe which contains a column called period that has datetime values in it in the following format:

2020-03-01T00:00:00.000000000

I want to convert the datetime to strings with the format – 03/01/2020 (month, day, year)

How would I do this?

Asked By: Bismah Ghafoor

||

Answers:

import pandas as pd

df = pd.DataFrame({'period': ['2020-03-01T00:00:00.000000000', '2020-04-01T00:00:00.000000000']})

df['period'] = pd.to_datetime(df['period'])

df['period'] = df['period'].dt.strftime('%m/%d/%Y')

print(df)

Output

   period
0  03/01/2020
1  04/01/2020
Answered By: Kreetchy

You can use the pandas to_datetime method to convert the string values in the ‘period’ column to a datetime object, and then use the strftime method to convert it to the desired string format.

Here’s an example code snippet that demonstrates how to achieve this:

import pandas as pd

# Sample dataframe
df = pd.DataFrame({'period': ['2020-03-01T00:00:00.000000000', '2020-04-15T00:00:00.000000000']})

# Convert the 'period' column to a datetime object
df['period'] = pd.to_datetime(df['period'])

# Convert the datetime object to the desired string format
df['period'] = df['period'].dt.strftime('%m/%d/%Y')

print(df)

In this example, we first create a sample dataframe with a ‘period’ column containing datetime strings. We then use the to_datetime method to convert these strings to a datetime object, and then use the strftime method to format the datetime object as a string with the desired format. Finally, we update the ‘period’ column in the dataframe with the formatted strings.

Answered By: Saeed Ahmad
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.