2014-10-20 252 views
0

我实际上试图从python 2.7.8中的csv文件中计算SLA。 这里是我的csv文件的例子:从csv文件中读取Python日期

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 

正如你可以看到有两个不同的日子是我的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 

我不知道如何正确使用Python中的“日期时间”功能,使你能帮助我解决我的问题。

+0

什么是输出的程序?任何错误消息? – greole 2014-10-20 08:40:52

+1

例如,您不需要使用'datetime.datetime.strptime()'创建常量日期值。'datetime.datetime(2014,9,26)'就可以。 – 2014-10-20 08:46:08

+2

但是,您未能告诉我们您的实际*问题*。有错误吗?意外的输出?你期望什么产出? – 2014-10-20 08:47:52

回答

5

尝试与模块命名为“熊猫”阅读:

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 

该函数返回的所有列和数据字典等中,你可以处理的格式。我在我的系统中命名了你的csv“日期”。一旦创建了字典,您可以打印您想要的信息或使用该数据。

希望这可以帮助你,我在一个星期前遇到类似于你的问题。

+1

我的csv文件被调用(“导出”)。你可以添加评论让我了解你的代码,请我在Python中是一个noob。 – Abolah 2014-10-20 09:48:30

+0

我添加注释以便于理解代码。文件的名称并不重要,只需在代码中将其更改为“日期”即可“导出”。你可以在[时间序列/日期功能](http://pandas.pydata.org/pandas-docs/stable/timeseries.html) – 2014-10-20 11:13:23

+0

找到一些关于pandas datetime模块的额外信息所以我厌倦了你的程序, t有一个很好的输出错误。这似乎适用于我的SLA计算,并且日期始终是正确的。非常感谢你 :) – Abolah 2014-10-20 13:01:25

3

我发现我的问题的解决方案,所以我在这里发布它。

#V1.2 du calcul de SLA 
#Cette version est opérationnelle 
import csv       # 
from datetime import datetime   #import the librairies 
from collections import defaultdict  # 

with open('/home/maxime/Bureau/Dev/Exports/export2.csv', 'rb') as fil: 
    values = defaultdict(int)    #create a dict 

    reader = csv.DictReader(fil, delimiter=';')   #read the csv file 
    for row in reader: 
     date = datetime.strptime(row['Dispatch date'], '%Y-%m-%d %H:%M:%S')  #datetime value in the right date format 
     values[date.strftime('%Y-%m-%d')] += 1   #increment the date with a step of 1 

    for date, value in sorted(values.items()): 
     result = (value/ 3927.2) * 100   #Sla calcul with the theoritic number of line 
     print 'Le fichier date du %s' % date  #SLA display 
     print 'Le SLA est de : %d%%' % result 
0

如果当天的文件中的数据进行分组,然后你可以使用itertools.groupby(),来计算SLA:

#!/usr/bin/env python 
import sys 
from datetime import datetime 
from itertools import groupby 

for day, group in groupby(sys.stdin, key=lambda line: line.partition(' ')[0]): 
    try: 
     date = datetime.strptime(day, '%Y-%m-%d') 
    except ValueError: 
     pass # ignore 
    else: 
     count = sum(1 for _ in group) 
     print('Le fichier date du {date:%Y-%m-%d}'.format(date=date)) 
     print('Le SLA est de {result:.2%}'.format(result=count/3927.2)) 

例子:

$ python compute-daily-sla.py < export2.csv