How to Add a Timestamp to a CSV File in Python

In this tutorial, we will learn how to append a timestamp to a CSV file using Python. Using Python to append a timestamp to a CSV file can prove to be very useful for tracking data changes over time.

We will first load the CSV file using the Pandas python library, add the timestamp column, and then save the updated CSV file.

Step 1: Install Required Libraries

To work with CSV files, we need to have the Pandas library installed. If you have not done so already, you can install it by running the below command in your terminal:

Step 2: Import Required Libraries

After installing the required library, the next step is to import it. We will also import the datetime module to generate the timestamp:

Step 3: Load the CSV file

To load the CSV file, we use the read_csv function from the Pandas library:

Step 4: Add the Timestamp

Next, we will add a new column to our dataframe with the current timestamp. Let’s call this column ‘Timestamp’:

Step 5: Save the CSV File

Lastly, we will save the updated dataframe to a new CSV file:

Full Code

Conclusion

To conclude, appending the timestamp to a CSV file in Python is quite easy. We just need to load the CSV file, add a new column for the timestamp, and then save the updated dataframe to a new CSV file.

The whole process only requires a few lines of code with the help of the powerful Pandas library.