获取指定日期后的连续1月/5月/9月的python方式

2024-04-26 13:41:25 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一些参考日期,试图找到下一个1月、5月、9月,例如,2016-02年之后的下一个相关日期应该是2016-05年。你知道吗

目前为我工作的方式(不是Python式的)看起来像:

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')

在大多数情况下,我们可以使用for循环来解决任何问题。但我们在这里试图避免for循环,因此我们称之为“pythonic”。没有for循环,工作日和月份肯定是不同的。你知道吗


Tags: reffordef方式dtstarttimestamptimedelta
1条回答
网友
1楼 · 发布于 2024-04-26 13:41:25

Pythonic是最简单的方法,也很容易阅读。所以这可能有点像Python。你知道吗

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))

相关问题 更多 >