1

I am trying to generate synthetic data with with date & time range. How can I include the needed date-time section in the program mentioned below?

import random
import sys
import math

latitude = 0.794501
longitude = -0.752568
file_n = 'random_lat_lon.csv'

def generate_random_data(lat, lon, num_rows, file_name):
    with open(file_name, 'w') as output:
        for _ in xrange(num_rows):
            hex1 = '%012x' % random.randrange(16**12)                
            flt = float(random.randint(0,100))
            dec_lat = random.random()/100
            dec_lon = random.random()/100
            output.write('%s,%.1f,%.6f,%.6f \n' % (hex1.lower(), flt, lon+dec_lon, lat+dec_lat))

generate_random_data(latitude, longitude, 600, file_n)

Include two columns of Start_DateTime & End_DateTime along other columns in the output.

Appreciate the help, Thank in advance.

Sitz Blogz
  • 1,061
  • 6
  • 30
  • 54

1 Answers1

1

You can generate random dates between a date range using datetime.timedelta, create a function that generates random start and end dates:

import datetime
import random

def get_random_dates():
    start = datetime.date(2007, 1, 1)
    end = datetime.date(2017, 1, 1)
    d1 = start + datetime.timedelta(
        seconds=random.randint(0, (end - start).total_seconds()))
    d2 = start + datetime.timedelta(
        seconds=random.randint(0, (end - start).total_seconds()))

    # make sure start_date is before end_date
    return sorted([d1, d2])

Then you can get random start and end times by calling the function:

startdatetime, enddatetime = get_random_dates()

And write these to your csv file along with other random generated data:

output.write('%s,%.1f,%.6f,%.6f,%s,%s \n' % (hex1.lower(), 
                                       flt, 
                                       lon+dec_lon, 
                                       lat+dec_lat,
                                       str(startdatetime),
                                       str(enddatetime)))
umutto
  • 7,460
  • 4
  • 43
  • 53
  • Thank you for the answer. I would need both datetime and location for the generation of random data. From a range of particular location I can get in the code posted in the question I want to include the datetime also in that. – Sitz Blogz May 18 '17 at 06:43
  • @SitzBlogz Do you mean how you can include the random_date in your output file? – umutto May 18 '17 at 06:48
  • Yes ..Include datetime to current output, as two columns, `startdatetime, enddatetime` May be have not mentioned it clearly apology for that .. – Sitz Blogz May 18 '17 at 06:50
  • Thank You so much .. I'll integrate the code into the mine and check .. – Sitz Blogz May 18 '17 at 07:16