【问题标题】:MySQL: Update multiple rows with random valuesMySQL:使用随机值更新多行
【发布时间】:2020-08-03 09:24:01
【问题描述】:

我有一张名为rainfall 的表。它有 2 列(sensorIDareatimerainfallredalert

我想在 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


    【解决方案1】:

    您只能使用 SQL 来完成:

    update rainfall  
    set time = concat(
      lpad(floor(rand() * 24), 2, '0'),
      ':',
      lpad(floor(rand() * 12) * 5, 2, '0')
    ); 
    

    【讨论】:

      【解决方案2】:

      我会使用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

      【讨论】:

      • 这要容易得多。但它会将其四舍五入到最接近的 5 秒。
      • @AhmedA:我的错!固定。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 2012-08-04
      • 1970-01-01
      • 2011-04-28
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多