简体   繁体   中英

Generate a random ISO8601 date with python?

I have seen how to go from ISO formatted date such as 2007-01-14T20:34:22+00:00 , to aa more readble format with python datetime .

Is there an easy way to generate a random ISO8601 date similar to this answer for datetime strings?

I'd suggest using this Faker library.

pip install faker

It's a package that allows you to generate a variety of randomised "fake" data sets. Using Faker below generates a random datetime object which you can then convert to an ISO8601 string format using the datetime.datetime.isoformat method.

import faker

fake = faker.Faker()
rand_date = fake.date_time()  # datetime(2006, 4, 30, 3, 1, 38)
rand_date_iso = rand_date.isoformat()  # '2006-04-30T03:01:38'
  1. Decide on which range you want the random dates to fall inside.
  2. Calculate the timestamp of those dates (seconds since unix epoch) in start , end integers.
  3. Use random.randrange(start, end) to pick a random number between start and end timestamps.
  4. Turn this random integer to datetime with datetime.fromtimestamp()
  5. Change the datetime to whatever output format you want.

If you wanted to just generate a random date, you could generate it to the correct format of the ISO8601 :

import random

iso_format = "{Year}-{Month}-{Day}T{Hour}:{Minute}+{Offset}"

year_range = [str(i) for i in range(1900, 2014)]
month_range = ["01","02","03","04","05","06","07","08","09","10","11","12"]
day_range = [str(i).zfill(2) for i in range(1,28)]
hour_range = [str(i).zfill(2) for i in range(0,24)]
min_range = [str(i).zfill(2) for i in range(0,60)]
offset = ["00:00"]

argz = {"Year": random.choice(year_range),
        "Month": random.choice(month_range),
        "Day" : random.choice(day_range),
        "Hour": random.choice(hour_range),
        "Minute": random.choice(min_range),
        "Offset": random.choice(offset)
        }

print iso_format.format(**argz)

This would need to be altered if you wanted to make sure the date was valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM