Adding a timestamp to an Excel file can be very useful when we need to track the changes done to the file. In this tutorial, we will learn how to add a timestamp to an Excel file using Python.
Steps:
1. First, we need to import the necessary modules. We will be using the pandas library to read and write the Excel files and the datetime module to get the current date and time.
1 2 |
import pandas as pd from datetime import datetime |
2. Next, we need to read the Excel file using pandas.
1 |
df = pd.read_excel('filename.xlsx') |
3. After that, we can add a new column to the dataframe with the name ‘Timestamp’. We can use the apply() method to apply a function to each row of the dataframe. In the function, we can use the datetime.now() method to get the current date and time.
1 |
df['Timestamp'] = df.apply(lambda x: datetime.now(), axis=1) |
4. Finally, we need to write the dataframe back to the Excel file using pandas.
1 |
df.to_excel('filename.xlsx', index=False) |
Here, the index=False argument is used to remove the index column from the Excel file.
Conclusion:
In this tutorial, we learned how to add a timestamp to an Excel file using Python. We used the pandas library to read and write the Excel files and the datetime module to get the current date and time.
Using the apply() method, we added a new column to the dataframe with the name ‘Timestamp’. Finally, we wrote the dataframe back to the Excel file using pandas.
Full Code:
1 2 3 4 5 6 |
import pandas as pd from datetime import datetime df = pd.read_excel('filename.xlsx') df['Timestamp'] = df.apply(lambda x: datetime.now(), axis=1) df.to_excel('filename.xlsx', index=False) |