Adding Timestamps in Existing CSV file
It is also possible to add timestamp to a CSV file that already contains some data. For this open the first file in read mode and the second file in write mode. Creating a csv reader object of the first file using the reader() function of csv module. reader() return a reader object which will iterate over lines in the given CSV file.
Append every data stored in the first file in rows variable using a for loop. Create a writer object of the second file using the writer() function of csv module. Now iterate over all the data in the rows variable using a for loop. Store the current date and time in a variable and then inserting it in the data at 0th index using the insert() function. Write the stored data in File2 using the writerow() function of csv module.
Example 1: Adding timestamp to existing data
Content of File1:
Python3
# Importing required modules import csv from datetime import datetime # creating a list to store the # existing data of CSV file rows = [] # Opening the CSV file in read mode using # the open() module with open (r 'FILE1.csv' , 'r' , newline = '') as file : # Opening another CSV file to in write mode # to add the data with open (r 'FILE2.csv' , 'w' , newline = '') as file2: # creating the csv reader reader = csv.reader( file , delimiter = ',' ) # storing the data of the csv file in a list for row in reader: rows.append(row) # creating the csv writer file_write = csv.writer(file2) # Iterating over all the data in the rows # variable for val in rows: # storing current date and time in a # variable current_date_time = datetime.now() val.insert( 0 , current_date_time) # writing the data in csv file file_write.writerow(val) |
Output:
How to add timestamp to CSV file in Python
Prerequisite: Datetime module
In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let’s the stepwise implementation for adding timestamp to CSV files in Python.