Python学习笔记:本月、上月、次月生成

一、需求

根据运行模型的需要,根据输入参数自动设置训练集、测试集和产生集的周期。

[En]

Due to the needs of the running model, the cycles of training set, test set and production set are set automatically according to the input parameters.

例如:本月输入”202203″,上月即为”202202″,次月为”202204″。

二、实操


import time, datetime, calendar

# 上月
def last_month(month):
    month = str(month)
    time_tuple = time.strptime(month, "%Y%m")
    year, month, day = time_tuple[:3]
    local_month = datetime.date(year, month, day).replace(day=1)
    last_month = (local_month - datetime.timedelta(days=1)).replace(day=1)
    last_month = last_month.strftime('%Y%m')
    last_month = int(last_month)
    return last_month

# 次月
def next_month(month):
    month = str(month)
    time_tuple = time.strptime(month, "%Y%m")
    year, month, day = time_tuple[:3]
    week, days_num = calendar.monthrange(year, month)
    local_month = datetime.date(year, month, day).replace(day=days_num)
    next_month = (local_month + datetime.timedelta(days=1)).replace(day=1)
    next_month = next_month.strftime('%Y%m')
    next_month = int(next_month)
    return next_month

# 定义取数月份
month = 202203

month_train = month
month_test = last_month(month)
month_predict = next_month(month)
print(r'训练集月份为:', month_train)
print(r'测试集月份为:', month_test)
print(r'预测集月份为:', month_predict)

'''
训练集月份为: 202203
测试集月份为: 202202
预测集月份为: 202204
'''

Original: https://www.cnblogs.com/hider/p/16337179.html
Author: Hider1214
Title: Python学习笔记:本月、上月、次月生成

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/10734/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部