【问题标题】:Get ISO-8601(SCORM 2004) Duration Format in Seconds using MySQL使用 MySQL 以秒为单位获取 ISO-8601(SCORM 2004)持续时间格式
【发布时间】:2015-10-16 13:53:27
【问题描述】:

我有一个带有类似值的 sql 列

PT2M52.37S
PT21.79S
PT53M29.68S
P
PT9S

是否有可能用一些MySQL 函数将上述格式转换为秒?

我已经搜索了所有内容,但没有找到与上述格式完全相同的内容。 我试过的任何日期 mysql 函数都不起作用。

有关此格式的更多信息:http://www.ostyn.com/standards/scorm/samples/ISOTimeForSCORM.htm

PHP 函数(它总是 P,第一个字符)

function scorm_format_duration($duration) {
    // Fetch date/time strings.
    $stryears = get_string('years');
    $strmonths = get_string('nummonths');
    $strdays = get_string('days');
    $strhours = get_string('hours');
    $strminutes = get_string('minutes');
    $strseconds = get_string('seconds');

    if ($duration[0] == 'P') {
        // If timestamp starts with 'P' - it's a SCORM 2004 format
        // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
        // and outputs filled sections, discarding leading zeroes and any format literals
        // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
        $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
                            '#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
                            '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
                            '#0*([\d.]+)S#', '#T#' );
        $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
                            '', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
                            '0.$1 '.$strseconds, '$1 '.$strseconds, '');
    } else {
        // Else we have SCORM 1.2 format there
        // first convert the timestamp to some SCORM 2004-like format for conveniency.
        $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
        // Then convert in the same way as SCORM 2004.
        $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
                            '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
        $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
                            '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
    }

    $result = preg_replace($pattern, $replace, $duration);

    return $result;
}

【问题讨论】:

  • 上述格式是 ISO 格式。我在问是否有任何准备使用的功能。如果是手动的,我什至不知道我们有什么样的不同可能性。在第一个示例中,虽然是 2 分 52 秒和 37 毫秒。
  • @GordonLinoff 是的,就是这样。
  • ISO-8601 涉及多种格式。这些看起来像durations。 IMX,大多数时候人们谈论 ISO-8601 和数据库,他们在谈论 ISO 日期或日期时间。您也许可以使用STR_TO_DATE(),但使用这种不同的格式可能不会很漂亮..
  • 似乎有人让它与STR_TO_DATE()here一起工作,他们的完整命令是SELECT STR_TO_DATE('PT13M22S', 'PT%iM%sS');,但遗憾的是它对我不起作用,不知道为什么。

标签: mysql sql datetime iso8601


【解决方案1】:

要使STR_TO_DATE 工作,您需要为微秒添加%f

SELECT duration,
CASE
    WHEN duration LIKE 'P%DT%H%M%.%S' THEN STR_TO_DATE(duration, 'P%dDT%HH%iM%s.%fS')
    WHEN duration LIKE 'P%DT%H%M%S' THEN STR_TO_DATE(duration, 'P%dDT%HH%iM%sS')
    WHEN duration LIKE 'PT%H%M%.%S' THEN STR_TO_DATE(duration, 'PT%HH%iM%s.%fS')
    WHEN duration LIKE 'PT%H%M%S' THEN STR_TO_DATE(duration, 'PT%HH%iM%sS')
    WHEN duration LIKE 'PT%M%.%S' THEN STR_TO_DATE(duration, 'PT%iM%s.%fS')
    WHEN duration LIKE 'PT%M%S' THEN STR_TO_DATE(duration, 'PT%iM%sS')
    WHEN duration LIKE 'PT%.%S' THEN STR_TO_DATE(duration, 'PT%s.%fS')
    WHEN duration LIKE 'PT%S' THEN STR_TO_DATE(duration, 'PT%sS')
END as session
FROM db

PT27M59.08S => 00:27:59.080000

PT2H27M37.11S => 02:27:37.110000

P4DT19H46M18.22S => 115:46:18.220000

【讨论】:

    【解决方案2】:

    我已经创建了 2 个函数来将 ISO8601 格式的 cmi.session_timecmi.total_time 的结果转换为秒:

    CREATE FUNCTION 'ISO8601_duration_delete_miliseconds'('isoDuration' VARCHAR(512)) RETURNS varchar(512) CHARSET latin1
    BEGIN
      DECLARE strIndex INT;
      DECLARE strRes varchar(512);
    
      SET strIndex = INSTR(isoDuration, '.');
      if (strIndex > 0) then
        set strRes = substring(isoDuration, 1, strIndex-1);
        set strRes = concat(strRes, 'S');
      else
        set strRes = isoDuration;
      end if;
    
      RETURN strRes;
    END
    

    以及最终的功能:

    CREATE FUNCTION `iso8601duration_to_seconds`(`isoDuration` VARCHAR(512)) RETURNS int(11)
    BEGIN
      DECLARE strIndex INT;
      DECLARE strRes varchar(512);
      DECLARE intRes INT;
    
      set strRes =  ISO8601_duration_delete_miliseconds(isoDuration);
    
      if (INSTR(isoDuration, 'H') > 0) then
        set intRes = time_to_sec(str_to_date(strRes, 'PT%HH%iM%sS'));
      elseif (INSTR(isoDuration, 'M') > 0) then
        set intRes = time_to_sec(str_to_date(strRes, 'PT%iM%sS'));
      else
        set intRes = time_to_sec(str_to_date(strRes, 'PT%sS'));
      end if;
    
      RETURN intRes;
    END
    

    【讨论】:

      【解决方案3】:

      我认为没有标准功能可以做到这一点。使用str_to_date() 是可能的,但它会因缺少时间组件而失败。如果你只有分钟和秒的组件,你可以用字符串操作来痛苦地做到这一点。

      select ((case when p like '%M%S'
                    then substring_index(substring_index(p, 'M', 2), 'M', -1)
                    when p like '%T%S'
                    then substring_index(substring_index(p, 'T', 2), 'T', -1)
                    else ''
               end) +
              (case when p like 'T%M'
                    then substring_index(substring_index(p, 'T', 2), 'T', -1) + 0
                    else 0
               end) * 60
              ) as seconds
      

      随着更多时间组件的添加,这并不容易概括。例如,当拆分器为“M”或“T”时,秒组件是第二个元素。有时,您只是想知道 ISO 委员会在制定这些标准时的想法。

      请注意,MySQL 使用前导数字(如果有)将字符串转换为数字。上面使用了这个特性。

      如果您支持更复杂的句号格式,那么我建议您编写一个用户定义的函数并将其发布在这里作为答案。

      我还要注意 SAS 支持这种格式。更好的是,他们有很好的documentation 解释它。

      编辑:

      您可以使用此组合更轻松地处理所有格式。它在每个组件之后插入一个空格,然后使用substring_index()

      select (case when newp like '%S'
                   then substring_index(substring_index(newp, 'S', 1), ' ', -1) + 1
                   else 0
              end) as seconds,
             (case when newp like '%M%'
                   then substring_index(substring_index(newp, 'M', 1), ' ', -1) + 1
                   else 0
              end) as minutes,
             . . .
      from (select replace(replace(replace(replace(replace(p, 'T', 'T '
                                                          ), 'Y', 'Y '
                                                  ), 'D', 'D '
                                          ), 'H', 'H '
                                  ), 'S', 'S '
                          ) as newp
            from t
           ) t
      

      【讨论】:

      • 您好,我编辑了我的第一篇文章,并附上了它的工作 PHP 代码版本。你能检查一下吗。谢谢
      • 它非常复杂,不支持秒。因为它也有毫秒。我们不能像在 PHP 中那样使用正则表达式吗?(第一篇文章)
      • @OhGodWhy 。 . .这应该可以在几毫秒内正常工作。 MySQL 会将 S 之前的值转换为数字,即使有小数点也是如此。 MySQL 不提供像用正则表达式替换这样的功能。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多