ajknzhol
ajknzhol

Reputation: 6450

Random Time Generation

I am Newbie to Python I am trying a little Random Time Generator which generates random time from the given initialize variable and ending at the given end variable for the 1000 records and have to save those 1000 records into database.

So Far i have reached is this code.

SQL.py

from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///sql.sqlite')
Base = declarative_base()
Session = sessionmaker(bind=engine)

session = Session()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    time = Column(Integer, default=None, index=True)

Base.metadata.create_all(engine)

Random.py

import datetime
import time
import random


MINTIME = datetime.datetime(2010,8,6,8,14,59)
MAXTIME = datetime.datetime(2013,8,6,8,14,59)
RECORDS = 1000

for RECORD in range(RECORDS):
    RANDOMTIME = random.randint(MINTIME, MAXTIME)
    print RANDOMTIME

It produces the traceback as this

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'

What i am doing wrong and if possible suggest some refactored method.

Upvotes: 3

Views: 2895

Answers (3)

Jon Clements
Jon Clements

Reputation: 142126

Use the start and end dates to determine the number of seconds between, then generate a random number between 0 and that, then add it to the start date, eg:

from datetime import datetime, timedelta
from random import randint

MINTIME = datetime(2010,8,6,8,14,59)
MAXTIME = datetime(2013,8,6,8,14,59)

PERIOD = (MAXTIME-MINTIME).total_seconds()
for n in range(1000):
    dt = MINTIME + timedelta(seconds=randint(0, PERIOD))
    # 2012-12-10 18:34:23 
    # etc...

Upvotes: 1

karthikr
karthikr

Reputation: 99620

Basically, the issue is: random.randint expects integers. So you should give it integers, and convert it back to datetime as you require

There could be a more efficient way, but here is one approach:

import datetime
import time

MINTIME = datetime.datetime(2010,8,6,8,14,59)
MAXTIME = datetime.datetime(2013,8,6,8,14,59)

mintime_ts = int(time.mktime(MINTIME.timetuple()))
maxtime_ts = int(time.mktime(MAXTIME.timetuple()))

for RECORD in range(RECORDS):
    random_ts = random.randint(mintime_ts, maxtime_ts)
    RANDOMTIME = datetime.datetime.fromtimestamp(random_ts)
    print RANDOMTIME

Upvotes: 5

Hugo Corrá
Hugo Corrá

Reputation: 14789

The problem is:

RANDOMTIME = random.randint(MINTIME, MAXTIME)

randint expects two integers, you are providing two dates.

you can do the following, considering the time is the same for MINTIME and MAXTIME:

for RECORD in range(RECORDS):
    n = random.randint(0,(MAXTIME-MINTIME).days)
    RANDOMTIME = MINTIME + datetime.deltatime(n)

Upvotes: 1

Related Questions