我是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'
我做错了,如果可能的话,建议一些重构的方法。
答案 0 :(得分:5)
基本上,问题是: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
答案 1 :(得分: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)
答案 2 :(得分:1)
使用开始日期和结束日期来确定之间的秒数,然后生成0到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...