简体   繁体   English

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

[英]Compare a datetime with a datetime range

I am fairly new to coding with Python and have so far managed to google my way out of most issues thanks to the great resources available on this site. 我对使用Python进行编码非常陌生,并且由于该站点上的大量资源,到目前为止,我已经设法设法解决了大多数问题。

I am writing a program which takes multiple .csv files, strips out the data from each of the initial files into different types of log files and writes these different types of logs into their own .csv. 我正在编写一个程序,该程序需要多个.csv文件,将每个初始文件中的数据剥离到不同类型的日志文件中,并将这些不同类型的日志写入它们自己的.csv中。

Now I have stripped the files back I have the need to roll through file A and for each row take the datetime and search file B for the same datetime and copy the relevant data into a new column alongside the initial data. 现在我已经将文件剥离了,我需要滚动浏览文件A,对于每一行,请选择日期时间,并在文件B中搜索相同的日期时间,然后将相关数据复制到初始数据旁边的新列中。 This is nice and easy with a if A == B for loop HOWEVER... each of these logs are written by different computers who's real time clock drifts over time. 如果循环的A == B,那么这很容易,但是...这些日志中的每条日志都是由不同的计算机编写的,这些计算机的实时时钟随时间漂移。 So what I actually want is to say take the time from file A and search for a corresponding time in file B +/- 30 seconds which is where I am stuck and have been gong around in circles for the last 3/4 hours! 因此,我实际上要说的是从文件A中抽出时间,并在文件B中搜索相应的时间+/- 30秒,这是我被卡住并在过去3/4个小时里绕圈旋转的地方!

Currently when I run the below code extract I get the following: 当前,当我运行以下代码提取时,我得到以下信息:

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

TypeError: can't compare datetime.datetime to datetime.date TypeError:无法将datetime.datetime与datetime.date进行比较

Thanks in advance! 提前致谢!

    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"  

You can't compare a datetime representing a specific point in time to a date , which represents a whole day. 您无法将代表特定时间点的datetime与代表一整天的date进行比较。 What time of day should the date represent? 日期应该代表一天中的什么时间?

ssptime is already a datetime (because that's what strptime returns) - why are you calling date on it? ssptime已经是一个datetime (因为这是strptime返回的结果)-为什么要在其上调用date This should work: 这应该工作:

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

Since your times are all down to second precision, you could also do this: 由于您的时间全都降至秒精度,因此您也可以这样做:

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

I'm not sure which is clearer - I'd probably lean towards the second. 我不确定哪个更清晰-我可能会倾向于第二个。

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

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