Home > Blockchain >  Generate random date in ISO date time format yyyy-MM-dd'T'HH:mm:ss. SSSXXX
Generate random date in ISO date time format yyyy-MM-dd'T'HH:mm:ss. SSSXXX

Time:03-12

It's my first time working with dates in Python. I am trying to generate a random date within a range in python the date format should be: yyyy-MM-dd'T'HH:mm:ss.SSSXXX timezone for example, "2022-10-31T01:30:00.000 05:00"

I also need to add an hour integer to the generated date, I am simulating a flight, so the first date is the departure and the second one the landing date.

CodePudding user response:

This is basically two different questions which you can join to get your result. I'm assuming you already have datetime objects.

Get a random date

You could generate a random date using an answer from another question:

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60)   delta.seconds
    random_second = randrange(int_delta)
    return start   timedelta(seconds=random_second)

which receives two datetime objects.

Usage:
d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

random_date(d1, d2)

Display date on desired format

You need to use .isoformat().

datetime(2019, 5, 18, 15, 17, 0, 0, tzinfo=timezone.utc).isoformat()

Output:

2019-05-18T15:17:00 00:00

CodePudding user response:

Something like this

from datetime import datetime,tzinfo,timedelta
from faker import Faker


class simple_utc(tzinfo):
    def tzname(self,**kwargs):
        return "UTC"
    def utcoffset(self, dt):
        return timedelta(0)


fake=Faker()
#define your range
randomdate=fake.date_time_between(start_date="-1d", end_date="now")
#add an hour
randomdatePlusHour=randomdate timedelta(hours=1)

print(randomdate.replace(tzinfo=simple_utc()).isoformat(),randomdatePlusHour.replace(tzinfo=simple_utc()).isoformat())

with the prerrequisit of faker (pip install faker).

  • Related