【发布时间】:2019-01-03 18:05:11
【问题描述】:
我正在做一个日期时间验证项目。具体来说,确保每个时间间隔都有一个日期时间。如果间隔中缺少日期时间,我会将缺少的值添加到 Timestamp 对象列表中。
当我运行以下代码时,它会将大多数日期时间标记为缺失,即使它们不是。我相信这是一个索引问题。我哪里错了?
代码:
import datetime
_RRATE_ = [0,1,0] #data refresh rate in [minute, hour, day]
LOCALE = "Seattle" #location of cell site
timesList = [] #initialize list of Timestamps with Errors filled in
#Class Timestamp allows us to store all data for a single timestamp in one object.
class Timestamp:
x = 1 #gives each new timestamp object a unique identifier for the dataset
missingStamps = 0
def __init__(self, datetime, location, errorMessage):
self.timestamp = datetime
self.location = location
self.error = errorMessage
self.UID = Timestamp.x
Timestamp.x+=1
timesList.append(self)
def updateError(self, newError):
self.error = newError
def __repr__(self): #make print timesList look neat
return str(self.UID) + " " + str(self.timestamp) + ", " + self.location + ", " + self.error
def duplicates(index):
tempList = []
for timestamp in timesList:
tempList.append(timestamp.timestamp)
if datetimes[index] in tempList:
Timestamp(datetimes[index],LOCALE, "duplicate")
return True
else:
return False
def outOfPlace(index):
for timestampObj in timesList:
if(timestampObj.timestamp > datetimes[index]):
Timestamp(datetimes[index],LOCALE, "out of place")
return True
else:
return False
def missingTimestamp(datetimeObj):
Timestamp.missingStamps = 0
if dateAdd(timesList[len(timesList)-1].timestamp) < datetimeObj:
while dateAdd(timesList[len(timesList)-1].timestamp) < datetimeObj:
Timestamp(dateAdd(timesList[len(timesList)-1].timestamp), LOCALE, "missing timestamp")
Timestamp.missingStamps+=1
return True
else:
return False
def dateAdd(datetimeObj):
return (datetimeObj + datetime.timedelta(minutes = _RRATE_[0], hours = _RRATE_[1], days = _RRATE_[2]))
def main():
Timestamp(datetimes[0],LOCALE, "no error")
errorCount = 0
for i in range(1,len(datetimes)):
if duplicates(i):
errorCount+=1
elif outOfPlace(i):
errorCount+=1
elif (missingTimestamp(datetimes[i]))>0:
errorCount+=Timestamp.missingStamps
Timestamp.missingStamps = 0
else:
Timestamp(datetimes[i],LOCALE, "no error")
for elem in timesList:
print elem
b = datetime.datetime(2018,7,20)
c = datetime.datetime(2018,7,20,1)
d = datetime.datetime(2018,7,20,2)
e = datetime.datetime(2018,7,20,7)
f = datetime.datetime(2018,7,20,7)
g = datetime.datetime(2018,7,20,9)
h = datetime.datetime(2018,7,20,16)
i = datetime.datetime(2018,7,20,16)
j = datetime.datetime(2018,7,20,9)
datetimes = [b,c,d,e,f,g,h,i,j]
main()
【问题讨论】:
-
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
标签: python python-2.7 indexing