To change the datetime format in Python pandas, you can use the strftime
method or the dt.strftime
accessor to format the datetime values in a DataFrame column. Here’s an example:
import pandas as pd
# Sample data
data = {'Date': ['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01'],
'Value': [10, 15, 8, 12]}
df = pd.DataFrame(data)
# Convert 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Set the desired date format
date_format = "%b %d, %Y"
# Format the 'Date' column
df['Formatted Date'] = df['Date'].dt.strftime(date_format)
print(df)
In this example, we have a DataFrame df
with a ‘Date’ column and a ‘Value’ column. We first convert the ‘Date’ column to a datetime format using pd.to_datetime()
.
Then, we set the desired date format using the date_format
variable. The %b
represents the abbreviated month name, %d
represents the day of the month with a leading zero, and %Y
represents the four-digit year.
To format the ‘Date’ column, we use df['Date'].dt.strftime(date_format)
to apply the formatting to each datetime value in the column. This returns a new Series with formatted date strings.
In the example, we create a new column ‘Formatted Date’ to store the formatted datetime values. You can assign the formatted values to an existing column or create a new column as per your requirements.
After running the code, you will see the DataFrame df
with the original ‘Date’ column and a new ‘Formatted Date’ column containing the datetime values in the desired format.
You can modify the date_format
variable to match your desired format. Refer to the Python documentation on strftime
for more formatting options: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
+ There are no comments
Add yours