Open In App

How to add timestamp to CSV file in Python

Last Updated : 23 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Creating CSV and adding timestamp

  • Import csv and datetime module. We will use the csv module to read and write the csv file and datetime module to add the current date and time in the csv file
  • Take the data from the user.
  • Open the CSV file in read and write mode (‘r+’) using open() function.
    • The open() function opens a file and returns its as a file-object.
    • newline = ‘ ‘ controls how universal newlines mode works. It can be None, ‘ ‘, ‘\n’, ‘\r’, and ‘\r\n’.
    • write() returns a writer object which is responsible for converting the user’s data into a delimited string.
  • Get current date and time using the datetime.now() function of datetime module.
  • Iterate over all the data in the rows variable with the help of a for loop.
  • Insert the current date and time at 0th index in every data using the insert() function.
  • Write the data using writerow() in the CSV file with the current date and time. 

Example 1: Add timestamp to CSV file

Python3




# Importing required modules
import csv
from datetime import datetime
  
  
# Here we are storing our data in a
# variable. We'll add this data in
# our csv file
rows = [['GeeksforGeeks1', 'GeeksforGeeks2'],
        ['GeeksforGeeks3', 'GeeksforGeeks4'],
        ['GeeksforGeeks5', 'GeeksforGeeks6']]
  
# Opening the CSV file in read and
# write mode using the open() module
with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file:
  
    # creating the csv writer
    file_write = csv.writer(file)
  
    # storing current date and time
    current_date_time = datetime.now()
  
    # Iterating over all the data in the rows 
    # variable
    for val in rows:
          
        # Inserting the date and time at 0th 
        # index
        val.insert(0, current_date_time)
          
        # writing the data in csv file
        file_write.writerow(val)


Output :

Example  2: Adding timestamp to CSV file

Python3




# Importing required modules
import csv
from datetime import datetime
  
  
# function to write in csv file
def write_in_csv(rows):
  
    # Opening the CSV file in read and
    # write mode using the open() module
    with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file:
  
        # creating the csv writer
        file_write = csv.writer(file)
  
        # Iterating over all the data in the rows 
        # variable
        for val in rows:
            
            # writing the data in csv file
            file_write.writerow(val)
  
  
# list to store the values of the rows
rows = []
  
# while loop to take
# inputs from the user
run = ''
while run != 'no':
  
    # lists to store the user data
    val = []
  
    # Taking inputs from the user
    val1 = input("Enter 1st value:- ")
    val2 = input("Enter 2nd value:- ")
    val3 = input("Enter 3rd value:- ")
  
    # storing current date and time
    current_date_time = datetime.now()
  
    # Appending the inputs in a list
    val.append(current_date_time)
    val.append(val1)
    val.append(val2)
    val.append(val3)
  
    # Taking input to add one more row
    # If user enters 'no' then the will loop will break
    run = input("Do you want to add one more row? Type Yes or No:- ")
    run = run.lower()
  
    # Adding the stored data in rows list
    rows.append(val)
  
# Calling function to write in csv file
write_in_csv(rows)


Output:

 

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:



Previous Article
Next Article

Similar Reads

Python | Pandas Timestamp.timestamp
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That z
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
How to add timestamp to excel file in Python
In this article, we will discuss how to add a timestamp to an excel file using Python. Modules requireddatetime: This module helps us to work with dates and times in Python.pip install datetimeopenpyxl: It is a Python library used for reading and writing Excel files.pip install openpyxltime: This module provides various time-related functions.Stepw
2 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
How to add a header to a CSV file in Python?
A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values a
2 min read
Add a Column to Existing CSV File in Python
Working with CSV files is a common task in data manipulation and analysis, and Python provides versatile tools to streamline this process. Here, we have an existing CSV file and our task is to add a new column to the existing CSV file in Python. In this article, we will see how we can add a column to a CSV file in Python. Add a New Column to Existi
3 min read
How to Add Numbers in a Csv File Using Python
When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data management CSV (Comma-Separated Values): A common
3 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
Python Script to change name of a file to its timestamp
A Digital Timestamp is a sequence of characters(usually a combination of digits and delimiters), identifying the time when a certain event occurred. In computer science, timestamps are generally used for marking the time of the creation of a virtual entity but are not limited to this in its use case. Digital Timestamps are implemented in various st
3 min read
Practice Tags :