在django中读取CSV文件

时间:2013-06-19 18:10:34

标签: django csv python-2.7

以下是我的代码

read_csv.py

from www.models import Attendance , Employee

import csv
import datetime

dataReader = csv.reader(open('www/attendace.csv'), delimiter=',', quotechar='"')

dic = {}
for row in dataReader:
    if row[0] != 'Ac-No': # Ignore the header row, import everything else
        account_number = row[0]
        stime = row[2]
        if account_number not in dic:
            dic[account_number] = []

        dic[account_number].append(stime)

for acc, stimes in dic.iteritems():
    checkin = stimes.pop(0)
    print checkin
    employee = Employee.objects.get(acc_no= acc)
    print str(employee.acc_no)

    d = checkin[:-4].strip()
    check_in = datetime.datetime.strptime(d, "%m/%d/%Y %H:%M" )

    check_out = None
    for stime in stimes:
        stime = stime[:-4].strip()
        stime = datetime.datetime.strptime(stime, "%m/%d/%Y %H:%M" )

        if stime.date() == check_in.date():
            check_out = stime
            print check_out
        else:
            attend = Attendance()
            attend.check_in = check_in
            attend.check_out = check_out
            attend.employee = employee
            attend.save()
            check_in = stime
            check_out= None

我希望每个account_numbercheck_incheck_out日期都有,所以我与员工account_numberstime列表( check_incheck_out在一起)。 问题是我只获得1名员工的输出和错误,例如emp 1有3条签入和结账记录,如果我继续运行员工1可以有30 ... 有人可以帮忙吗?

0 个答案:

没有答案