Python implements an example method for generating random date strings

  • 2020-06-19 10:48:45
  • OfStack

This article is an example of an Python implementation that generates random date strings. To share for your reference, specific as follows:

Generates a random date string for insertion into the database.

Set a time period through the time tuple, and the start and end times are converted to timestamps.

One of the timestamps is randomly selected and regenerated into a time tuple, which is then formatted into a string


import time
import random
a1=(1976,1,1,0,0,0,0,0,0)       # Set the start date time tuple ( 1976-01-01 00 : 00 : 00 ) 
a2=(1990,12,31,23,59,59,0,0,0)  # Set the end date time tuple ( 1990-12-31 23 : 59 : 59 ) 
start=time.mktime(a1)  # Generate the start timestamp 
end=time.mktime(a2)   # Generate the end timestamp 
# Randomly generated 10 Date string 
for i in range(10):
  t=random.randint(start,end)  # Randomly pulled out from the start and end timestamps 1 a 
  date_touple=time.localtime(t)     # Generates a time tuple for the timestamp 
  date=time.strftime("%Y-%m-%d",date_touple) # Convert the time tuple to a formatted string ( 1976-05-21 ) 
  print(date)

The result is:


1985-11-29
1990-08-29
1977-10-16
1985-03-30
1985-05-14
1988-12-01
1979-10-11
1988-09-11
1985-11-13
1983-03-27

PS: Here are some more online tools for calculating dates and days:

Online Date/Day calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online perpetual calendar:
http://tools.ofstack.com/bianmin/wannianli

Online Lunar/Solar Calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

More about Python related content interested readers to view this site project: "skills summary Python date and time", "Python math skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful in Python programming.


Related articles: