Skip to content

Instantly share code, notes, and snippets.

@rg3915
Last active February 18, 2023 15:09
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rg3915/db907d7455a4949dbe69 to your computer and use it in GitHub Desktop.
Save rg3915/db907d7455a4949dbe69 to your computer and use it in GitHub Desktop.
Generate Random Datetime Python
import random
from datetime import datetime, timedelta
min_year=1900
max_year=datetime.now().year
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year+1
end = start + timedelta(days=365 * years)
for i in range(10):
random_date = start + (end - start) * random.random()
print(random_date)
#done
# or a function
def gen_datetime(min_year=1900, max_year=datetime.now().year):
# generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year + 1
end = start + timedelta(days=365 * years)
return start + (end - start) * random.random()
@luka-bediashvili
Copy link

how would you get it in the form DD/MM/YYYY currently 1971-08-18 18:24:09.033866

@Faguilar-V
Copy link

Very good implemetation, thanks

Copy link

ghost commented Feb 8, 2019

Thanks for sharing! ! Works nice!

@last2win
Copy link

thank you

Copy link

ghost commented Jan 29, 2020

Top sweet

@ByteBaker
Copy link

Use pip install randomtimestamp

@yousef200509
Copy link

how would you get it in the form DD/MM/YYYY currently 1971-08-18 18:24:09.033866

new_random_date = random_date.split("\n")
print(new_random_date[0])

@ByteBaker
Copy link

how would you get it in the form DD/MM/YYYY currently 1971-08-18 18:24:09.033866

`
from randomtimestamp import randomtimestamp

random_date = randomtimestamp(text=False).strftime("%d/%m/%Y")

random_date = '30/05/1967' # example
`

@norohind
Copy link

Just thank you!

@rufatpro
Copy link

rufatpro commented Jul 5, 2022

Thank you!

@hasansalimkanmaz
Copy link

Thank you!

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