我有一張桌子叫rainfall. 它有 2 列(sensorID,area, time,rainfall,redalert)我想以 5 分鐘的間隔用隨機時間填充時間列(例如 12:55、04:30、07:45)。我設法通過使用此 Python 代碼獲得了隨機時間:import mysql.connectorimport randomimport datetimeimport timeMINTIME = datetime.datetime(2020,4,1,0,0,0)MAXTIME = datetime.datetime(2020,7,1,0,0,0)mintime_str = int(time.mktime(MINTIME.timetuple())) #convert date to INTmaxtime_str = int(time.mktime(MAXTIME.timetuple())) #convert date to INTno_steps = (maxtime_str - mintime_str)//(5*6) #state the number of minutes interval to 5 minutessql = "UPDATE rainfall SET date = %s"rand = ''for RECORD in range(108): random_slot = random.randint(0, no_steps) random_ts = mintime_str + 5*60 * random_slot RANDOMTIME = datetime.datetime.fromtimestamp(random_ts) rand = datetime.datetime.strftime(RANDOMTIME, '%H:%M')val = (rand,)mycursor.execute(sql, val)raindb.commit()print(mycursor.rowcount, "record(s) affected")問題是這段代碼只用 1 個值及時填充所有行:我需要在每一行中使用不同的值。如果某些行具有重復的時間值,那很好。
2 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
你只能用 SQL 來做:
update rainfall
set time = concat(
lpad(floor(rand() * 24), 2, '0'),
':',
lpad(floor(rand() * 12) * 5, 2, '0')
);

MYYA
TA貢獻1868條經驗 獲得超4個贊
我會使用rand()
如下:
update rainfall set time = sec_to_time(floor(rand() * 60 * 60 * 24 / (5 * 60) * 5 * 60)
表達式rand() * 60 * 60 * 24
為您提供代表時間的隨機秒數。然后您可以使用floor()
和乘法將其四舍五入到最接近的 5 分鐘。最后,time_to_sec()
把它變成一個time
.
添加回答
舉報
0/150
提交
取消