Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose a random month from the past 2 years in Python

Tags:

python

random

I would like to choose a random month between the current year and 2016. This is my current, very naive, solution

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

It's obvious that this set will get too large in the future so what would be a better way of achieving this?

like image 688
jinyus Avatar asked Dec 17 '22 22:12

jinyus


2 Answers

May be you can have two list of month and year since, these will be fixed. Then, you can randomly choose between each and make a date to return. That way I think then no need to generate all different dates and no need to store in large list:

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

Result:

'2017-05'

Update

Just in case if there is limitation on not exceeding current month if the year selected is current year then, you may need if condition for generating list of months as below:

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
like image 59
student Avatar answered Dec 20 '22 10:12

student


You can use the library pandas and use date_range

choice(pd.date_range(start="2016-01-01", end="2018-01-01", freq='M'))

If you want it until today, you can just substitute the startand end arguments for whatever suitable, e.g.

from dateutil.relativedelta import relativedelta
today = datetime.today()
two_years_ago = today - relativedelta(years=2)
choice(pd.date_range(start=two_years_ago, end=today, freq='M'))
like image 25
rafaelc Avatar answered Dec 20 '22 11:12

rafaelc