How can I subtract a fixed date from a columns of date in excel file using Python? -


i have file below format:

name           date sam          21/1/2003 bil          5/4/2006 sam          4/7/2009 mali         24/7/2009 bil          13/2/2008 etc... 

i want set fix date instance: 1/1/2003 , subtract of dates fix date , divide them week find out names registered in weeks , put them in set. below final result:

sam=[week3,week12] bil=[week25,week13] etc.. 

i have write below python script not working.i have error:

 val=set(start_date-'date(data.files.datetime)') typeerror: unsupported operand type(s) -: 'int' , 'str' 

anyone has idea best way write code it?

import pprint import csv   open('d:/results/names_info.csv', 'r') csvfile:     start_date= 1/1/2003     filereader=csv.reader(csvfile,'excel')     row in filereader:          name in row:              key=name              val=set(start_date-'date(data.files.datetime)')              datedict[key]=val   pprint.pprint (datedict) 

you have several errors in code:

  1. not ignoring first line of csv file contains 'name' , 'date'.
  2. using strings store dates instead of date type.
  3. attempting subtract 1 string another.
  4. modifying items in datedict without first checking exist.
  5. the slashes in 1/1/2003 going treated divide signs , result 0.

here code these errors fixed:

import csv collections import defaultdict import datetime datetime import date import math  def weeks(filename, start_date):     # defaultdict class create items when key accessed     # not exist     datedict = defaultdict(set)     open(filename, 'r') csvfile:         filereader = csv.reader(csvfile, 'excel')         read_header = false         row in filereader:             # ignore first row of file             if not read_header:                 read_header = true                 continue              # strip out whitespace             cells = [col.strip() col in row]             name = cells[0]             date_str = cells[1]              # parse date string date             row_date = datetime.datetime.strptime(date_str, '%d/%m/%y').date()              # calculate difference between dates             delta = start_date-row_date             # convert days weeks, use math.floor() here if             # needed             delta_weeks = int(math.ceil(delta.days / 7.0))              datedict[name].add(delta_weeks)      return datedict  date_dict = weeks('a.csv', start_date=date(year=2013, month=1, day=1)) name, dates in date_dict.iteritems():     print name, list(dates) 

this prints out:

bil [351, 254] sam [519, 182] mali [179] 

you should able figure out how print 'weeks'.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -