从过去 2 年的 Python 中随机选择一个月份

jin*_*yus 4 python random

我想在当前年份和 2016 年之间随机选择一个月份。这是我目前非常幼稚的解决方案

from random import choice
def get_month():
    return choice({'2018-06','2018-05','2018-04','2018-03'})
Run Code Online (Sandbox Code Playgroud)

很明显,这个集合在未来会变得太大,那么实现这一目标的更好方法是什么?

stu*_*ent 5

也许你可以有两个月份和年份的列表,这些将被修复。然后,您可以在每个之间随机选择并确定返回日期。这样我认为不需要生成所有不同的日期,也不需要存储在大列表中:

from random import choice
def get_month():
    months = list(range(1, 13)) # 12 months list
    year = list(range(2016, 2019)) # years list here
    val = '{}-{:02d}'.format(choice(year), choice(months))
    return val

get_month()
Run Code Online (Sandbox Code Playgroud)

结果:

'2017-05'
Run Code Online (Sandbox Code Playgroud)

更新

以防万一如果选择的年份是当前年份,则不超过当前月份的限制,您可能需要if生成月份列表的条件如下:

from random import choice
from datetime import datetime

def get_month():

    today = datetime.today() # get current date
    year = list(range(2016, today.year+1)) # list till current date year

    # randomly select year and create list of month based on year
    random_year = choice(year)

    # if current year then do not exceed than current month
    if random_year == today.year:
        months = list(range(1, today.month+1))
    else:
        # if year is not current year then it is less so can create 12 months list
        months = list(range(1, 13)) 

    val = '{}-{:02d}'.format(random_year, choice(months))

    return val
Run Code Online (Sandbox Code Playgroud)