【发布时间】:2020-08-03 09:24:01
【问题描述】:
我有一张名为rainfall 的表。它有 2 列(sensorID、area、time、rainfall、redalert)
我想在 time 列中填充 5 分钟间隔的随机时间(例如 12:55、04:30、07:45)。我设法通过使用此 Python 代码获得了随机时间:
import mysql.connector
import random
import datetime
import time
MINTIME = 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 INT
maxtime_str = int(time.mktime(MAXTIME.timetuple())) #convert date to INT
no_steps = (maxtime_str - mintime_str)//(5*6) #state the number of minutes interval to 5 minutes
sql = "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")
问题是这段代码在 time 中仅用 1 个值填充所有行:
我需要在每一行中使用不同的值。如果某些行有重复的时间值也没关系。
提前致谢
【问题讨论】:
标签: python mysql random sql-update date-arithmetic