Skip to content

Instantly share code, notes, and snippets.

@knu2xs
Last active July 17, 2023 14:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save knu2xs/8ca7e0a39bf26f736ef7 to your computer and use it in GitHub Desktop.
Save knu2xs/8ca7e0a39bf26f736ef7 to your computer and use it in GitHub Desktop.
Use python function to generate random date in given calendar year.
# import modules
import random
import datetime
# create function accepting a single parameter, the year as a four digit number
def get_random_date(year):
# try to get a date
try:
return datetime.datetime.strptime('{} {}'.format(random.randint(1, 366), year), '%j %Y')
# if the value happens to be in the leap year range, try again
except ValueError:
get_random_date(year)
@eliasdorneles
Copy link

Thanks for sharing!
Note: the code is missing the return in the recursion ;-)

@mousewanderer
Copy link

Thanks for the code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment