Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python select random date in current year

In Python can you select a random date from a year. e.g. if the year was 2010 a date returned could be 15/06/2010

like image 845
John Avatar asked Jan 21 '11 13:01

John


3 Answers

It's much simpler to use ordinal dates (according to which today's 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 before 1AD.

like image 114
Michael Dunn Avatar answered Nov 19 '22 04:11

Michael Dunn


Not directly, but you could add a random number of days to January 1st. I guess 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))
like image 29
AndiDog Avatar answered Nov 19 '22 06:11

AndiDog


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: Ordinal dates as used in Michael Dunns answer are way better to use then timestamps! One might want to combine the use of ordinals with this though.

like image 32
plundra Avatar answered Nov 19 '22 04:11

plundra