Python select random date in current year

John picture John · Jan 21, 2011 · Viewed 12.1k times · Source

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

Answer

Michael Dunn picture Michael Dunn · Jan 21, 2011

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.