Insert timestamp into filename when exporting into .csv

  • 8 months ago
Comment

ChatGPT
1 / 1

To insert a timestamp into a filename when exporting to a CSV file in Python, you can use the datetime module to generate the timestamp and then concatenate it with your desired filename. Here's an example:

python
import csv
from datetime import datetime

# Generate a timestamp string
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

# Your original filename
original_filename = "data.csv"

# Create a new filename with the timestamp
new_filename = f"exported_{timestamp}_{original_filename}"

# Your data to export
data = [
["Name", "Age"],
["Alice", 25],
["Bob", 30],
["Eve", 28]
]

# Write data to the new CSV file
with open(new_filename, "w", newline="") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)

print(f"Data exported to {new_filename}")

In this example, the timestamp is generated using the strftime method of the datetime object. It formats the current date and time as YYYYMMDD_HHMMSS. You can adjust the format to suit your preference.

Replace the example data and filename with your own data and filenames. This code will create a new CSV file with a filename that includes the timestamp.