找到指定日期最近的日期 [英] Find the closest date to a given date

查看:135
本文介绍了找到指定日期最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datetime对象数组,我想找到数组中最接近给定日期的元素(例如 datetime.datetime(2014,12,16)



帖子显示如何查找不在给定日期之前的最近日期 。如何更改此代码,以便可以返回给定日期之前的日期?



例如,如果数组包含元素 datetime。日期时间(2014,12,10) datetime.datetime(2014,12,28),原来的项目应该是最接近的到 datetime.datetime(2014,12,16)的绝对值。

解决方案

$($,$)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c>

请注意,这也适用于数字。


I have an array of datetime objects, and I would like to find which element in the array is the closest to a given date (e.g datetime.datetime(2014,12,16))

This post shows how to find the nearest date which is not before the given date. How can I alter this code so that it can return dates that are before a given date?

For example, if the array housed elements datetime.datetime(2014,12,10) and datetime.datetime(2014,12,28), the former item should be returned because it is closest to datetime.datetime(2014,12,16) in absolute value.

解决方案

def nearest(items, pivot):
    return min(items, key=lambda x: abs(x - pivot))

Note that this will work for numbers too.

这篇关于找到指定日期最近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆