将日期时间列表与Python中的日期时间进行比较

栏目: Python · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/14143100/compare-list-of-datetimes-with-datetime-in-python

我有一个日期时间对象列表,并希望找到在特定时间范围内的对象:

import datetime

dates = [ datetime.datetime(2007, 1, 2, 0, 1),
          datetime.datetime(2007, 1, 3, 0, 2),
          datetime.datetime(2007, 1, 4, 0, 3),
          datetime.datetime(2007, 1, 5, 0, 4),
          datetime.datetime(2007, 1, 6, 0, 5),
          datetime.datetime(2007, 1, 7, 0, 6) ]
#in reality this is a list of over 25000 dates

mask = (dates>datetime.datetime(2007,1,3)) & \
       (dates<datetime.datetime(2007,1,6))

但是,这会导致以下错误:

“TypeError:无法将datetime.datetime与列表进行比较”

我该如何修复我的代码?

如果您的日期列表按 排序 顺序排列,则可以使用 bisect module

>>> import bisect
>>> bisect.bisect_right(dates, datetime.datetime(2007,1,3))
1
>>> bisect.bisect_left(dates, datetime.datetime(2007,1,6))
4

.bisect_ *函数将索引返回到日期列表中:

>>> lower = bisect.bisect_right(dates, datetime.datetime(2007,1,3))
>>> upper = bisect.bisect_left(dates, datetime.datetime(2007,1,6))
>>> mask = dates[lower:upper]
>>> mask
[datetime.datetime(2007, 1, 3, 0, 2), datetime.datetime(2007, 1, 4, 0, 3), datetime.datetime(2007, 1, 5, 0, 4)]

翻译自:https://stackoverflow.com/questions/14143100/compare-list-of-datetimes-with-datetime-in-python


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Programming Interface

The Linux Programming Interface

Michael Kerrisk / No Starch Press / 2010-11-6 / GBP 79.99

The Linux Programming Interface describes the Linux API (application programming interface)-the system calls, library functions, and other low-level interfaces that are used, directly or indirectly, b......一起来看看 《The Linux Programming Interface》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器