简体   繁体   English

在Python中找到给定日期的间隔

[英]find the interval of a given date in python

I'm struggling with date objects in python. 我在用Python处理日期对象。

I have the following data: 我有以下数据:

from datetime import datetime, timedelta 
# date retrieved from a list
ini =  [u'2016-01-01']
# transform the ini in a readable string
ini2 = ', '.join(map(str, ini))
# transform the string a date object
date_1 = datetime.strptime(ini2, "%Y-%m-%d")
# number that is the length of the date
l = 365.0
# adding l to ini2
final = date_1 + timedelta(days = l)

Now I'd need to split the whole interval (that is the period from date_1 to final ) by an input number (eg ts = 4) and, given another input date (eg new_date = u'2016-05-19' ) check in which interval it is (in the example 19th of May is in t2 = 2). 现在我需要分割整个区间(即从周期date_1final )由输入数量(例如TS = 4),并给定的另一输入日期(例如new_date = u'2016-05-19' )检查在其中间隔是(在五月的例子19在T2 = 2)。

I hope I made myself clear enough. 我希望我已经足够清楚了。

Thanks I tried different approaches but none seems the right one. 谢谢,我尝试了不同的方法,但似乎没有一个正确的方法。

This might help: 这可能会有所帮助:

from datetime import datetime, timedelta


def which_interval(date0, delta, date1, n_intervals):
    date0 = datetime.strptime(date0, '%Y-%m-%d')
    delta = timedelta(days = delta)
    date1 = datetime.strptime(date1, '%Y-%m-%d')
    delta1 = date1 - date0
    quadrile = int(((float(delta1.days) / delta.days) * n_intervals))
    return quadrile


# Example: figure out which quarter August 1st is in
interval = which_interval(
    '2016-01-01',
    366,
    '2016-08-01',
    4)
print '2016-08-01 is in interval %d, Q%d'%(interval, interval+1)

Note that this function uses python indices so it will start at quarter 0 and end at quarter 3. If you want 1-based indices (so the answer will be 1, 2, 3, or 4) you would want to add 1 to the result. 请注意,此函数使用python索引,因此它将从四分之一开始,到四分之一结束。如果您要基于1的索引(因此答案将是1、2、3或4),则需要将1加到结果。

the timedelta object supports division, so use floor division by a step and you will get an interval in range(ts) timedelta对象支持除法,因此step使用地板除法,您将获得一个range(ts)的间隔

new_date = datetime.strptime(u'2016-05-19', "%Y-%m-%d")

ts = 4
step = timedelta(days=l)/ts #divide by the number of steps

interval = (new_date - date_1)//step #get the number this interval is in

so for date_1 <= new_date < date_1 + step interval will be 0, for date_1+step<=new_date < date_1 + step*2 interval will be 1, etc. 因此对于date_1 <= new_date < date_1 + step间隔将为0,对于date_1+step<=new_date < date_1 + step*2间隔将为1, date_1+step<=new_date < date_1 + step*2

This of course is using python style indices so to get the number starting from 1, add one: 当然,这是使用python样式索引,因此要获取从1开始的数字,请添加一个:

 interval = (new_date - date_1)//step + 1

EDIT: the functionality to divide timedelta objects was only added in python3, you would need to use the .total_seconds() method to do the calculation in python 2: 编辑:仅在python3中添加了划分timedelta对象的功能,您需要使用.total_seconds()方法在python 2中进行计算:

step = timedelta(days=l).total_seconds()/ts #divide by inteval

interval =  (new_date - date_1).total_seconds()//step

You could calculate this using the seconds total of the intervals. 您可以使用间隔的总秒数来计算。

import math
from datetime import datetime, timedelta 

l = 365.0
factor = 4
date_1 = datetime.strptime('2016-01-01', "%Y-%m-%d")
lookup_dt = datetime.strptime('2016-12-01', "%Y-%m-%d")

def get_interval_num(factor, start_dt, td, lookup_dt):
    final = start_dt + td
    interval = (final - start_dt).total_seconds()
    subinterval = interval / factor
    interval_2 = (lookup_dt - start_dt).total_seconds()
    return int(math.ceil(interval_2 / subinterval))

num = get_interval_num(
    factor=factor,
    start_dt=date_1,
    td= timedelta(days=l),
    lookup_dt=lookup_dt
)
print("The interval number is: %s" % num)

Output would be: 输出为:

The interval number is: 4

EDIT: clearified variable naming, extended code snippet 编辑:明确的变量命名,扩展的代码片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM