0

Given some reference date, trying to find the next Jan, May, Sep, e.g. the next relevant date after 2016-02 should be 2016-05.

Current way that working for me (not pythonic) looks like:

def rel_month(dt):
    rel_mon = [1, 5, 9]
    ref_dt = pd.Timestamp(dt)
    idx = pd.DatetimeIndex(start=ref_dt, end=ref_dt + pd.Timedelta('122D'), freq='M')
    return idx[idx.month.isin(rel_mon)][0].strftime('%Y-%m')

In most case we can use for loop to solve ANY problem. But we are trying to avoid for loops here, hence the title "pythonic". Without for loops, weekday is definitely different from month.

Alpha
  • 2,372
  • 3
  • 21
  • 23
  • 3
    If this is working and you are only looking for style you could also try the [coderview stackexchange](https://codereview.stackexchange.com/). – syntonym Apr 08 '18 at 08:15
  • Possible duplicate of [Find the date for the first Monday after a given a date](https://stackoverflow.com/questions/6558535/find-the-date-for-the-first-monday-after-a-given-a-date) – Peter Wood Apr 08 '18 at 08:48
  • @PeterWood try not to use for loop to solve this problem, hence the title "pythonic". so not the same as weekday != month – Alpha Apr 08 '18 at 08:54

1 Answers1

1

Pythonic is the easiest way and easy to read. So this might be slightly pythonic.

import pandas as pd
def rel_month(dt):
    #assign fitting month to each month (
    rel_mon = {1:1,2:5,3:5,4:5,5:5,6:9,7:9,8:9,9:9,10:1,11:1,12:1}
    ref_dt = pd.Timestamp(dt)
    month = ref_dt.month
    new_month = rel_mon[month]

    # maybe change year
    year = ref_dt.year
    if month > 9:
        year += 1
    #returns formatted string
    return '{}-{}'.format(year,str(new_month).zfill(2))