python – 随机时间生成

我是
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'

我做错了什么,如果可能的话,建议一些重构的方法.

最佳答案 基本上,问题是:
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
点赞