How to add timestamp to csv file in Python?


CSV files are a simple and widely used format for storing and exchanging data, sometimes we may need to add a timestamp to the CSV file, such as when we want to keep track of when the data was collected or updated. In this article, we will explore how to add a timestamp to a CSV file in Python. We will discuss different methods for adding a timestamp, such as using the datetime module and the pandas library. We will also provide step-by-step instructions and code examples to help you get started with adding a timestamp to your CSV files.

DateTime module

A datetime module can be used to work with both the date and the time as there are no date or time data types in Python. Python already has the DateTime module built in, so we don't need to install it separately.

Date and time manipulation classes are available in the Python DateTime module. Dates, times, and periods of time are the main parameters of the methods included in these frameworks. Because Date and DateTime are objects in Python rather than texts or timestamps, any modifications you make to them will have the same effect.

CSV module of Python

The Python csv module makes it possible to work with Comma Separated Values (CSV) files, which are a common way to store tabular data. The module has methods for reading and writing CSV files, parsing CSV data, and manipulating it.

The csv module has classes that can write and read data that is in tabular form in CSV format. It lets programmers say things like "write this data in the format that Excel wants" or "read data from this file that Excel made" without having to know the exact details of the CSV format that Excel uses. Users can also describe the CSV formats that other applications can understand or make their own CSV formats for specific purposes.

The writer and reader objects of the csv module are used to read and write sequences. With the DictReader and DictWriter classes, programmers can also read and write data in the form of dictionaries.

Adding a timestamp to a new csv file in Python

Steps to add timestamp to a new file

  • Importing the datetime and CSV modules. The csv module will be used to receive and write the csv file, while the datetime module will be utilized to append the current date and time to the csv file.

  • Get data from the user that we want to add to the file.

  • Use the open() function to open the CSV file in read and write mode ('r+').

  • The open() function opens a file and gives back a file object that represents the file.

  • How universal newlines mode works is controlled by the newline = “” setting. It can be None, "," "n," "r," or "rn."

  • write() gives back a writer object that is in charge of turning the user's data into a string with spaces.

  • Use the datetime to get the current date and time.

  • datetime module has a function called now().

  • With the help of a for loop, go through all of the data in the rows variable.

  • Using insert() function, you can put the current date and time at the 0th index of every data.

  • With the current date and time, use writerow() to write the data to the CSV file.

Example

# Importing all the important required modules
import csv
from datetime import datetime

# We will be storing data in the variable r
# After that we will add this data to our CSV file
r = [['Tutorialspoint', '--'],
   ['Simply', 'Easy'],
   ['learning', 'at fingertips']]

# Use open() module to open the CSV file
# open csv file in read and write mode
with open(r'C:/Users/Tutorialspoint/Desktop/sample2.csv', 'r+', newline='') as f:

   # create the csv writer
   fwrite = csv.writer(f)

   # Now we will store current time and date
   current_dnt = datetime.now()

   # Iterating over each and every data in the r variable
   for v in r:
      
      # Inserting the date and time at 0th
      # index
      v.insert(0, current_dnt)
      
      # writing the data in csv file
      fwrite.writerow(v)

Output

Adding a timestamp to an existing csv file in Python

Firstly, open the file that already exists in read mode and the new file in write mode. Using the reader() function of the CSV module to turn the first file into a CSV reader object. reader() gives you an object that will go through each line in a CSV file.

Use a for loop to add all of the information in the first file to the rows variable. Use the writer() function of the CSV module to make a writer object for the second file. Now, use a for loop to go through all the data in the rows variable. Store the current date and time in a variable. Then, use the insert() function to put it in the data at the 0th index. Use the writerow() function of the CSV module to put the data that has been saved in File2 instead.

Example

import csv
from datetime import datetime
# We will create a list where we can store content of the file 
r = []

# open the existing csv file in the read mode
with open(r'C:/Users/Tutorialspoint/Desktop/industry.csv', 'r', newline='') as f:
   
   # Opening new CSV file to in write mode
   # to add the data
   with open(r'C:/Users/Tutorialspoint/Desktop/sample.csv', 'w', newline='') as f2:

      # creating the csv reader
      reader = csv.reader(f, delimiter=',')

      # we will store the data of existing foile in r
      for row in reader:
         r.append(row)

      # creating the csv writer
      f_write = csv.writer(f2)

      # Iterating over all the data in the r variable
      for v in r:

         # storing current date and time in a variable
         current_dt = datetime.now()
         v.insert(0, current_dt)
         
         # writing the data in csv file
         f_write.writerow(v)

Output

Conclusion

In this article, we learned that a module called datetime can be used to work with both the date and the time and we can use CSV module to manipulate CSV files. We have seen how can we add timestamps to new or existing files using Python.

Updated on: 31-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements