7

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

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

0

3 Answers 3

15

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'
Sign up to request clarification or add additional context in comments.

Comments

6
  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.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.