我的代码中有一个这样的矩阵,带有unix时间戳:
event_sequences = [
[1368136883, 1368137089], #The first event is never empty
[1368214777, 1368214966],
[],
.... There are the perfect number of days (empty arrays) in the gaps between the existing events.
[],
[1368747495, 1368747833],
[1368830501, 1368831869]
]
对于event_sequences中的每个事件,我知道它的开始和结束(start = event_sequences[n][0]
和end = event_sequences[n][1]
)。正如您所看到的,有些事件是空的,我必须采取的方法是将这些空事件的开始和结束设置为记录最后一个事件后一天的00:00和23:59。像
[
[start, end],
[start, end],
[the day after the last event at 00:00, the day after the last event at 23:59]
]
空事件的开始和结束也需要是unix时间戳。我怎么能在python中做到这一点?
答案 0 :(得分:0)
以下应该可以解决问题。但是要注意几个问题/事情:
event_sequences
中的第一个元素是空列表event_sequences
中的天数是否应该有差距?例如,您可以在下面的输出中看到,即使在空白条目填写完成后,您在2013年5月12日到2013年5月16日之间的序列中也存在差距。代码:
from datetime import datetime, timedelta
import time
event_sequences = [
[1368136883, 1368137089],
[1368214777, 1368214966],
[],
[],
[1368747495, 1368747833],
[1368830501, 1368831869]
]
#take the last_day recorded date as a datetime object from the event_sequences and return a 2-element list
#with the unix timestamps for 00:00 and 23:59
def getNextDay(last_day):
next_day = last_day + timedelta(days=1)
next_day_start = next_day.replace(hour=0,minute=0,second=0)
next_day_end = next_day.replace(hour=23,minute=59,second=0)
return [int(next_day_start.strftime("%s")), int(next_day_end.strftime("%s"))]
def fillEmptyDates(event_list):
new_event_list = []
#note: this will fail if the first element in the list of event_sequences is blank
last_day = int(time.time())
for x in event_sequences:
if len(x) == 0:
next_day = getNextDay(last_day)
last_day = datetime.utcfromtimestamp(next_day[1])
else:
next_day = x
last_day = datetime.utcfromtimestamp(next_day[1])
new_event_list.append(next_day)
return new_event_list
new_event_sequence = fillEmptyDates(event_sequences)
print new_event_sequence
#[[1368136883, 1368137089], [1368214777, 1368214966], [1368230400, 1368316740], [1368316800, 1368403140], [1368747495, 1368747833], [1368830501, 1368831869]]
for event in new_event_sequence:
print str(datetime.utcfromtimestamp(event[0]))+ ' and '+str(datetime.utcfromtimestamp(event[1]))
#2013-05-09 22:01:23 and 2013-05-09 22:04:49
#2013-05-10 19:39:37 and 2013-05-10 19:42:46
#2013-05-11 00:00:00 and 2013-05-11 23:59:00
#2013-05-12 00:00:00 and 2013-05-12 23:59:00
#2013-05-16 23:38:15 and 2013-05-16 23:43:53
#2013-05-17 22:41:41 and 2013-05-17 23:04:29