Python picks random date in current year

In Python, you can select a random date from a year. for example, if the year was in 2010, the date may be 06/15/2010

+7
source share
4 answers

It is much easier to use ordinal dates (according to which today the date is 734158):

from datetime import date import random start_date = date.today().replace(day=1, month=1).toordinal() end_date = date.today().toordinal() random_day = date.fromordinal(random.randint(start_date, end_date)) 

This will fail for dates prior to 1AD.

+19
source

Not directly, but you can add a random number of days until January 1. I think the following should work for the Gregorian calendar:

 from datetime import date, timedelta import random import calendar # Assuming you want a random day of the current year firstJan = date.today().replace(day=1, month=1) randomDay = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364)) 
+3
source
 import datetime, time import random def year_start(year): return time.mktime(datetime.date(year, 1, 1).timetuple()) def rand_day(year): stamp = random.randrange(year_start(year), year_start(year + 1)) return datetime.date.fromtimestamp(stamp) 

Edit: The starting dates used in Michael Dunns answer are better to use timestamps then! You might want to combine the use of ordinals with this.

+1
source
 import calendar import datetime import random def generate_random_date(future=True, years=1): today = datetime.date.today() #Set the default dates day = today.day year = today.year month = today.month if future: year = random.randint(year, year + years) month = random.randint(month, 12) date_range = calendar.monthrange(year, month)[1] #dates possible this month day = random.randint(day + 1, date_range) #1 day in the future else: year = random.randint(year, year - years) month = random.randint(1, month) day = random.randint(1, day - 1) return datetime.date(year, month, day) 
0
source

All Articles