从生成的数组列表中查找缺少的时间

2024-10-03 11:12:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在从MySQL数据库收集数据生成的列表中查找缺失的时间。这意味着每次函数运行时,测试列表值总是不同的

我的代码:

def get_time_slotes():
    test_list = sorted([u'08:00', u'12:00', u'13:00', u'09:00', u'10:00', u'17:00'])

    res = list(set(range(max(test_list) + 1)) - set(test_list)) 
    print("The list of missing elements : " + str(res))


if __name__ == "__main__":
    get_time_slotes()

但我收到了这个错误:

Traceback (most recent call last):
  File "/Users/liesching/Documents/test.py", line 41, in <module>
    get_time_slotes()
  File "/Users/liesching/Documents/test.py", line 36, in get_time_slotes
    res = list(set(range(max(test_list) + 1)) - set(test_list)) 
TypeError: coercing to Unicode: need string or buffer, int found

如果这有什么不同的话,我正在使用Python2.7。这是一个限制,因为我正在一个已经存在的应用程序之上构建


Tags: pytest列表gettimerangeresusers
3条回答

问题是max(test_list)返回u'17:00',因此需要将其转换为17,因为范围取整数。然后还需要对set(test_list)中的每个项目执行此操作,然后将数字转换回时间。例如:

def get_hour(time):
  """ u'08:00' -> 8 """
  return int(time.split(":")[0])

def get_time(hour):
  """ 8 -> u'08:00' """
  return (u'%s:00' % hour).zfill(5)
   
def get_time_slotes():
    test_list = sorted([u'08:00', u'12:00', u'13:00', u'09:00', u'10:00', u'17:00'])

    res = map(get_time, list(set(range(get_hour(max(test_list)) + 1)) - set(map(get_hour, test_list))))
    print("The list of missing elements : " + str(res))


if __name__ == "__main__":
    get_time_slotes()

我用datetime解决了你的问题。首先,我用utf-8编码每个元素

代码不是很干净,但是很有效

from datetime import datetime, timedelta, time

def get_time_slotes():

    list_of_times = [u'08:00', u'12:00', u'13:00', u'09:00', u'10:00', u'17:00']
    test_list = sorted(datetime.strptime(x.encode('utf-8'),'%H:%M').time() for x in list_of_times)
    
    res = [x.strftime("%H:%M") for x in sorted(set(time(x,0,0,0) for x in range(max(test_list).hour)) - set(test_list))]

    print("The list of missing elements : " + str(res))

输出:

The list of missing elements : ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '11:00', '14:00', '15:00', '16:00']

您的问题是将unicode连接到int:

u'17:00' + 1

如果您分析时间,可能会更容易完成任务,例如:

from datetime import datetime

def get_time_slotes():
    test_list = [u'08:00', u'12:00', u'13:00', u'09:00', u'10:00', u'17:00']
    test_list = [datetime.strptime(t, '%H:%M').hour for t in test_list]

    res = set(range(max(test_list) + 1)) - set(test_list)
    print("The list of missing elements : " + str(res))

get_time_slotes()

输出:

The list of missing elements : {0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16}

相关问题 更多 >