2016-09-09 2 views
1

저는 파이썬으로 코딩하는 데 상당히 익숙하며,이 사이트에서 제공되는 훌륭한 리소스 덕분에 대부분의 문제를 해결할 수있었습니다.날짜 시간대와 datetime 범위 비교

여러 개의 .csv 파일을 사용하는 프로그램을 작성하고 각 초기 파일의 데이터를 다른 유형의 로그 파일로 분리하고 이러한 여러 유형의 로그를 자신의 .csv에 씁니다.

이제는 파일 A를 롤오버해야하고 각 행에 대해 datetime을 사용하고 동일한 datetime에 대해 B 파일을 검색하고 관련 데이터를 초기 데이터와 함께 새 열로 복사해야합니다. 이것은 A == B for 루프를 사용하는 것이 좋고 쉽습니다. 그러나 ...이 로그 각각은 실시간 시계가 시간이 지남에 따라 다른 컴퓨터에 의해 작성됩니다. 그래서 실제로 원하는 것은 파일 A에서 시간을 가져 와서 파일 B +/- 30 초에 해당 시간을 검색합니다.이 시간은 내가 붙어 있고 지난 3/4 시간 동안 원으로 돌아 다녔습니다! 나는 아래의 코드 추출을 실행할 때

가 현재 나는 다음과 같은 얻을 :

---> 35 경우 (타임 코드 - 마진) < = datetime.datetime.date (ssptime) < = (타임 코드 + 마진) :

형식 오류 : 사전에 datetime.date

덕분에 datetime.datetime을 비교할 수 없습니다!

import matplotlib.pyplot as plt # external function need from inside Canopy 
import os # external functions 
import re # external functions 
import matplotlib.patches as mpatches 
import csv 
import pandas as pd 
import datetime 


addrbase = "23" 
csvnum = [1,2,3,4,5] # CSV number 
csvnum2 = [1,2,3,4,5] 
senstyp = ['BSL'] #Sensor Type 
Beacons = 5 





outfile = open('C:\Users\xxx\Canopy\2303_AVG2.csv', 'w') #File to write to 
outcsv = csv.writer(outfile, lineterminator='\n') 

with open('C:\Users\xxx\Canopy\2303_AVG.csv', 'r') as f: #File read vairable f 
    csvread = csv.reader(f, delimiter=',') #Stores the data from file location f in csvread using the delimiter of',' 
    for row in csvread: #sets up a for loop using the data in csvread 
     timecode = datetime.datetime.strptime(row[1],'%Y/%m/%d %H:%M:%S')#BSL time to datetime.datetime 
     margin = datetime.timedelta(seconds = 30) 

     with open('C:\Users\xxx\Canopy\2301_SSP_AVG.csv', 'r') as f: #File read vairable f 
      csvreadssp = csv.reader(f, delimiter=',') 
      for line in csvreadssp: 
       ssptime = datetime.datetime.strptime(row[2],'%Y/%m/%d %H:%M:%S')# 
       print ssptime 
       if (timecode - margin) <= datetime.datetime.date(ssptime) <= (timecode + margin): 
        relssp = line[6] 
        print "Time: " + str(timecode) + " SSP: " + str(relssp) 
     #try: 
        row.append(relssp) #Calculates the one way travel time of the range and adds a new column with the data 
        outcsv.writerow(row) # Writes file 
     #except ValueError: #handles errors from header files 
     # row.append(0) #handles errors from header files 
outfile.flush()   
outfile.close()  
print "done" 

답변

2

당신은 하루 종일을 나타내는 date에 특정 시점을 나타내는 datetime을 비교할 수 없습니다. 날짜가 몇시를 나타내야합니까?

ssptime은 이미 datetime입니다. (그 이유는 strptime이 반환하기 때문입니다) - date에 전화하는 이유는 무엇입니까? 이 작업을해야합니다 :

if (timecode - margin) <= ssptime <= (timecode + margin): 

당신의 시간은 모든 초 정밀도까지, 당신은 또한이 작업을 수행 할 수 있기 때문에 :

if abs((ssptime - timecode).total_seconds()) < margin: 

나는 명확 확실하지 않다 - 나는 아마도 향하다 것 둘째.

+1

예. Date/datetime을 표현할 때 날짜, 시간, datetime, timedelta 및 tzinfo와 같은 여러 클래스가 있습니다. 동일한 클래스에 대해서만 비교 연산을 수행 할 수 있습니다. 그렇지 않으면 TypeError가 발생합니다. 파이썬 날짜 유형 문서 https://docs.python.org/2/library/datetime.html을 참조하십시오. – rojeeer