从csv文件读取Python日期

Abo*_*lah 0 python csv format datetime

我实际上是在尝试从python 2.7.8中的csv文件计算SLA.这是我的csv文件的一个例子:

2014-09-24 23:57:43;0000B169;20
2014-09-24 23:58:05;00012223;20
2014-09-24 23:58:49;00012200;20
2014-09-24 23:59:33;0000B0EA;21
2014-09-25 00:00:17;000121FF;21
2014-09-25 00:00:39;00012217;21
2014-09-25 00:01:01;00012176;20
2014-09-25 00:01:23;00012175;20
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我的CSV文件有两天不同,我希望我的程序能够读取它们并每天计算SLA.这是我的计划:

#V1.1 du programme de Calcul du SLA
import csv
import datetime
with open("/home/maxime/Bureau/Dev/Exports/export2.csv", 'rb') as f:            #import the required modules
    reader = csv.reader(f, delimiter=';')
    count=0              #variable of the date "number"
    for row in reader:
    if row[0] !="Dispatch date":                # we don't want to include the first line of the first column
        date = datetime.datetime.strptime (row [0],"%Y-%m-%d %H:%M:%S")             #creating the datetime object with the string agrument
        if date < datetime.datetime.strptime ("2014-09-26 00:00:00", "%Y-%m-%d %H:%M:%S")and date > datetime.datetime.strptime ("2014-09-25 00:00:00", "%Y-%m-%d %H:%M:%S"):        #loop to calcul if the date is correct or not
        count = count+1                 #increment the date to perform the SLA calcul
    result = (count/3927.2)*100                 #SLA calcul
    print "Le fichier date du", date                #
    print "Le SLA est de :", result, "%"            #Display the SLA and the date of the file
Run Code Online (Sandbox Code Playgroud)

我不知道如何正确使用python中的"datetime"函数,所以你能帮我解决我的问题.

Car*_*eño 6

尝试阅读名为"pandas"的模块:

import pandas as pd
def importdict(filename):#creates a function to read the csv
    #create data frame from csv with pandas module
    df=pd.read_csv(filename+'.csv', names=['systemtime', 'Var1', 'var2'],sep=';',parse_dates=[0]) #or:, infer_datetime_format=True)
    fileDATES=df.T.to_dict().values()#export the data frame to a python dictionary
    return fileDATES #return the dictionary to work with it outside the function
if __name__ == '__main__':
    fileDATES = importdict('dates') #start the function with the name of the file
Run Code Online (Sandbox Code Playgroud)

此函数返回一个字典,其中包含您可以使用的格式的所有列和数据.我在你的系统中命名了你的csv"日期".创建dict后,您可以打印所需的信息或使用数据.

希望这可以帮助你,一周前我遇到了类似于你的问题.