2013-12-17 133 views
2

我是Python的新手我想要一個小的隨機時間發生器,它從給定的初始化變量產生隨機時間,並在1000個記錄的給定最終變量結束,並且必須將那1000個記錄保存到數據庫中。隨機時間生成

到目前爲止我已經達到了這個代碼。

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 

它產生回溯,因爲這

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

什麼,我做錯了,如果可能的話建議一些重構方法。

回答

3

基本上,問題是:random.randint expects integers。所以,你應該給它整數,並將其轉換回日期時間,你需要

可能是一種更有效的方式,但這裏有一個方法:

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 
+0

真棒。像魅力一樣工作。謝謝 – ajkumar25

1

的問題是:

RANDOMTIME = random.randint(MINTIME, MAXTIME) 

randint預計兩個整數,您所提供的兩個日期。

你能做到以下幾點,考慮的時間是MINTIME和MAXTIME相同:

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

好的如何糾正? 'RANDOMTIME = random.randint(INT(MINTIME),INT(MAXTIME))' 產生 '類型錯誤:INT()參數必須是字符串或數字,而不是「datetime.datetime'' – ajkumar25

1

使用的開始和結束日期確定之間的秒數,然後生成一個介於0和那個之間的隨機數,然後將其添加到開始日期,例如:

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