繁体   English   中英

比较日期时间和日期时间范围

[英]Compare a datetime with a datetime range

我对使用Python进行编码非常陌生,并且由于该站点上的大量资源,到目前为止,我已经设法设法解决了大多数问题。

我正在编写一个程序,该程序需要多个.csv文件,将每个初始文件中的数据剥离到不同类型的日志文件中,并将这些不同类型的日志写入它们自己的.csv中。

现在我已经将文件剥离了,我需要滚动浏览文件A,对于每一行,请选择日期时间,并在文件B中搜索相同的日期时间,然后将相关数据复制到初始数据旁边的新列中。 如果循环的A == B,那么这很容易,但是...这些日志中的每条日志都是由不同的计算机编写的,这些计算机的实时时钟随时间漂移。 因此,我实际上要说的是从文件A中抽出时间,并在文件B中搜索相应的时间+/- 30秒,这是我被卡住并在过去3/4个小时里绕圈旋转的地方!

当前,当我运行以下代码提取时,我得到以下信息:

---> 35 if(时间码-保证金)<= datetime.datetime.date(ssptime)<=(时间码+保证金):

TypeError:无法将datetime.datetime与datetime.date进行比较

提前致谢!

    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"  

您无法将代表特定时间点的datetime与代表一整天的date进行比较。 日期应该代表一天中的什么时间?

ssptime已经是一个datetime (因为这是strptime返回的结果)-为什么要在其上调用date 这应该工作:

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

由于您的时间全都降至秒精度,因此您也可以这样做:

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

我不确定哪个更清晰-我可能会倾向于第二个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM