简体   繁体   中英

find the interval of a given date in python

I'm struggling with date objects in 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).

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.

the timedelta object supports division, so use floor division by a step and you will get an interval in 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.

This of course is using python style indices so to get the number starting from 1, add one:

 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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