【问题标题】:Format Datatype for Time in MySQLMySQL中时间的格式数据类型
【发布时间】:2018-08-30 04:31:35
【问题描述】:
result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'")
equipments = result.map { |print_this| [print_this['sourcetime'], print_this['description']] }
p equipments

MySQL 工作台中sourcetime 的数据类型设置为 TIME

我得到的结果是2000-01-01 12:00:04 +0100

我只想获取时间12:00:04 并删除日期和+0100

【问题讨论】:

  • 你的问题我不清楚。您要解决的问题是什么:如何格式化输出(提示:strftime)?或者如何将时区更改为 UTC?
  • @spickermann 是的,我想格式化输出

标签: mysql ruby time


【解决方案1】:

你能试试strftime("%I:%M%p")

equipments = result.map { |print_this| print_this.sourcetime.strftime("%I:%M%p") }

【讨论】:

  • 'sourcetime' 是我的列名。有没有其他方法可以添加 .strftime("%I:%M%p")
  • 如果你保存在字符串日期,只需转换成日期例如:) sourcetime.to_date.strftime("%I:%M%p")
  • 我已编辑以显示我的完整代码。我的“源时间”在一个嵌套数组中。我不知道如何将其放入字符串中进行转换。
【解决方案2】:

实现这一点需要两个步骤:

  1. Time.parse 从数据库返回的字符串到Time 的实例中。
  2. 使用Time#strftime 将Time 的实例格式化为所需的输出格式。

要仅显示时间的小时、分钟和秒(没有日期和时区信息),请使用 '%H:%M:%S' 指令(有关更多示例,请参阅 docs)。

require 'time' # `Time.parse` is not Ruby Core but from the Standard Library

equipments = result.map do |record| 
  [
    Time.parse(record['sourcetime']).strftime('%H:%M:%S'), 
    record['description']
  ]
end

【讨论】:

  • 不错!我可以为未来的用户添加 .to_s 以防止错误Time.parse(record['sourcetime'].to_s).strftime('%H:%M:%S')
  • 没有to_s 会出现什么样的错误? pg 以字符串表示形式返回日期和时间列,不需要对已经是字符串的内容调用 to_s。
  • no implicit conversion of Time into String
  • 哇,这出乎意料。如果返回字符串或时间,它似乎取决于设置或 gem 版本。跳过Time.parse 部分你的情况,record['sourcetime'].strftime('%H:%M:%S') 应该在你的上下文中工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 2015-12-11
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多