Md. Mahim Muntasir
Md. Mahim Muntasir

Reputation: 23

How do i add timestamp on the first column while writing a csv from list of string

I am trying to write a list of string data2 = {'yslow_score': 54, 'dom_content_loaded_time': 7679, 'page_elements': 112} to a CSV file which I was able to do. but I need to add timestamp on the 1st column. below is my code

with open('mycsvfile.csv','w') as f:
w = csv.writer(f)
w.writerow(data2.keys())
w.writerow(data2.values())

I used below code to write the timestamp. but it's not as per my required format

for val in data2:
    now = time.strftime('%d-%m-%Y %H:%M:%S')
    w.writerow([now, val])

Upvotes: 1

Views: 1204

Answers (2)

gehbiszumeis
gehbiszumeis

Reputation: 3711

You can also use pandas dataframe

import pandas as pd
import time

# Transform your dictionary to pandas dataframe
df = pd.DataFrame.from_records([data2], index=[0])

# Insert timestamp at first column (as desired)
df.insert(0, 'timestamp', time.strftime('%d-%m-%Y %H:%M:%S'))

# Write to csv
df.to_csv('my_file.csv', index=False)

That should do it, the way you wanted!

Upvotes: 1

Surya Tej
Surya Tej

Reputation: 1392

You could use Dict Writer Method to write to CSV Files This Code works for Python 3

import csv
import time
data2 = {'yslow_score': 54, 'dom_content_loaded_time': 7679, 'page_elements': 112}
with open(path, 'w', newline="") as f:
  fieldnames = ['Timestamp', 'yslow_score', 'dom_content_loaded_time', 'page_elements']
  writer = csv.DictWriter(f, fieldnames=fieldnames)
  writer.writeheader()
  now = time.strftime('%d-%m-%Y %H:%M:%S')
  print(now)
  writer.writerow({'Timestamp': now, 'yslow_score': data2['yslow_score'], 'dom_content_loaded_time': data2['dom_content_loaded_time'], 'page_elements': data2['page_elements']})

output snapshot

Upvotes: 0

Related Questions