2014-10-20 253 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