1

i have a sample CSV given as follows:

Name,Birthdate,Age,Address,Zone
ABC,3-10-2016 11:00:00AM,21,XYZ Street 21, zone
BCD,3-11-2016 15:54:00PM,22,WXY Street 21/A, S zone
CDW,4-11-2015 21:09:00PM,22,ZYX Street 21Avenue, North Zone

i have used the following code to obtain the weekday from a given date in the data:

import csv
from datetime import datetime


with open(filename, 'rb') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
         birthdate = row['Birthdate']  # keys are named in the first row of your CSV
         birthdate = datetime.strptime(birthdate, '%m-%d-%Y %H:%M:%S%p')
         print birthdate.strftime('%A')

The output was:

Thursday
Friday
Saturday  

i want to append this output into the same CSV with a new column name as weekday .

NOTE: the above code and data are all sampled and original data is way different.

2
  • See Add columns to CSV while writing the CSV for how you could do in-place CSV updating. Commented Mar 11, 2016 at 11:22
  • @MartijnPieters The solution didn't helped me much though. But i am in a seek of some base script which can write the obtained values into a new column. Commented Mar 11, 2016 at 12:40

1 Answer 1

2

Just for fun

import re
from datetime import datetime as dt

def changedate(birthdate):
    weekday = dt.strptime(birthdate, '%m-%d-%Y %H:%M:%S%p').strftime('%A')
    return birthdate + ',' + weekday

str = open(filename).read()
str = re.sub(r'Name,Birthdate,Age,Address','Name,Birthdate,Weekday,Age,Address', str)
str = re.sub(r'(\d+-\d+-\d+\s\d+:\d+:\d+\w{2})',lambda m: changedate(m.group()), str)

with open(filename, 'w') as f:
    f.write(str)
Sign up to request clarification or add additional context in comments.

6 Comments

what if we don't want to use lambda? any generic and simple way to do it?
Hundred ways to do that stackoverflow.com/search?q=Add+columns+to+CSV+python choose whatever you like.
i used your approach for better results. thanks much. but when i re run this script then a new weekday column is also created. that as if i run this script again and again then weekday will be added as many times as i run the script. ANy way to control this?
p = re.compile(ur'(\d+-\d+-\d+\s\d{2}:\d{2}:\d{2}\w{2})(?=(?:,[^,]+){3}$)', re.MULTILINE) str = re.sub(p, lambda m: changedate(m.group()), str) add (?:,[^,]+){3} for counting number of columns after date column
please update the answer for better understanding. thanks. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.