Python - 按日期时间对象对 python 列表进行排序
我有一个日期时间对象列表,它通过一个名为 Django Recurrence 的附加库从我的数据库附加到一个数组中。
我将其附加在 for 循环中,如下所示:
events = Events.objects.filter(...some conditions)
timeslots = []
for event in events:
for occurence in event.recurrences.between(context['today'], context['end']):
occurence_date = datetime.combine(occurence.date(), time(0, 0))
timeslots.append({
'start_date': occurence_date + timedelta(hours=event.start_time.hour, minutes=event.start_time.minute),
'end_date': occurence_date + timedelta(hours=event.end_time.hour, minutes=event.end_time.minute),
})
然后它将输出为 [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, {'start_date': datetime.datetime(2022, 3, 8, 14, 0), ... }]
这太棒了。
事件循环的一个副作用是,它会在所有事件发生后添加其他事件,例如 3 月 1 日、3 月 5 日、3 月 10 日、3 月 2 日、3 月 4 日等等。我想订购它们在开始日期之前,这样我就可以在模板中以正确的顺序呈现它们。
谢谢
I have a list of datetime objects that's being appended into an array from my database with an additional library called Django Recurrence.
I append it as follows inside a for loop:
events = Events.objects.filter(...some conditions)
timeslots = []
for event in events:
for occurence in event.recurrences.between(context['today'], context['end']):
occurence_date = datetime.combine(occurence.date(), time(0, 0))
timeslots.append({
'start_date': occurence_date + timedelta(hours=event.start_time.hour, minutes=event.start_time.minute),
'end_date': occurence_date + timedelta(hours=event.end_time.hour, minutes=event.end_time.minute),
})
It would then output it as [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, {'start_date': datetime.datetime(2022, 3, 8, 14, 0), ... }]
which is great.
A side effect from the events loop, is that it would add a the other events, after all the occurrences, eg 1 march, 5 march, 10 march, 2 march, 4 march, etc etc etc. I'd like to order them by the starting date, so I can render them out in the correct order in my template.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想对字典列表进行排序,你可以使用
sorted
,但你必须传递你想要排序的
key
,如下所示:If you want to sort a list of dictionaries, you can use
sorted
,but you have to pass the
key
you want to sort with, something like this:您可以尝试
sorted
它接受两个参数:一个可迭代对象和一个键。后者指示函数应如何对前一个参数(数组)进行排序。我生成了一个更明确的示例:输出
You can try
sorted
which takes two arguments: An iterable object, and a key. The latter indicates how the function should sort the former argument(array). I have generated an example to be more explicit:Output