Last active
July 17, 2023 14:15
-
-
Save knu2xs/8ca7e0a39bf26f736ef7 to your computer and use it in GitHub Desktop.
Use python function to generate random date in given calendar year.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!
Note: the code is missing the
return
in the recursion ;-)