How To Change Date Format To yyyy-mm-dd In CSV File Using Python

Working with dates in different formats can be a bit challenging, especially when dealing with CSV files. In this tutorial, we’ll learn how to change the date format to yyyy-mm-dd in a CSV file using Python.

This will make the dates easy to sort, filter and work with. We’ll be using the popular Pandas library to achieve this.

Step 1: Install Pandas

If you haven’t already, the first step is to install the Pandas library. You can do this using the following command:

Step 2: Load the CSV File into a Pandas DataFrame

Assuming you have a CSV file with dates in a different format, let’s load it into a Pandas DataFrame. Here’s an example of what the CSV file content might look like:

Date,Value
12-05-2021,100
11-05-2021,200
10-05-2021,300

You can use the following code to load the CSV file into a DataFrame:

Step 3: Change the Date Format

In this step, we’ll convert the dates in the DataFrame to the yyyy-mm-dd format using the pd.to_datetime() function:

Step 4: Save the DataFrame to a New CSV File

Now that the date format has been changed, we’ll save the DataFrame to a new CSV file:

Full Code

Output

   Date  Value
0 2021-05-12    100
1 2021-05-11    200
2 2021-05-10    300
The dates in the new CSV file are in yyyy-mm-dd format!

Conclusion

We’ve successfully changed the date format to yyyy-mm-dd in a CSV file using Python and Pandas. This will make it much easier to work with dates in your datasets. You can now sort, filter or analyze dates more easily and consistently.