如何将十进制时间转换为时间格式

如何将十进制时间转换为时间格式

本文介绍了如何将十进制时间转换为时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算两个时间间隔之间的差.我可以做到,但是我只能得到小数部分的差异,我想知道如何将其转换为"Minutes:Second"中的格式.

I would like to calculate the difference between two time-sets. I can do this, but I only get the difference in decimals and I would like to know how to convert them to format as in "Minutes:Second".

因此,我将分钟和秒作为字符:

So, I have the minutes and the seconds as characters:

video_begin <- c("8:14", "4:47", "8:27", "4:59", "4:57", "7:51", "6:11", "5:30")
video_end <- c("39:08", "47:10", "49:51", "44:31", "39:41", "47:12", "40:13", "46:52")

我用as.POSIXct将它们转换为时间值,进行df运算,然后将差值添加到第三列,简单易用...

I convert them into time values with as.POSIXct, make a df and add the difference as a third column, easy peasy...

video_begin <- as.POSIXct(video_begin, format = "%M:%S")
video_end <- as.POSIXct(video_end, format = "%M:%S")
video <- data.frame(video_begin, video_end)
video$video_duration <- video_end - video_begin

这就是我从视频中获得的信息:

And this is what I get for video:

  video_begin         video_end            video_duration
1 2017-09-12 00:08:14 2017-09-12 00:39:08  30.90000 mins
2 2017-09-12 00:04:47 2017-09-12 00:47:10  42.38333 mins
3 2017-09-12 00:08:27 2017-09-12 00:49:51  41.40000 mins
4 2017-09-12 00:04:59 2017-09-12 00:44:31  39.53333 mins
5 2017-09-12 00:04:57 2017-09-12 00:39:41  34.73333 mins
6 2017-09-12 00:07:51 2017-09-12 00:47:12  39.35000 mins
7 2017-09-12 00:06:11 2017-09-12 00:40:13  34.03333 mins
8 2017-09-12 00:05:30 2017-09-12 00:46:52  41.36667 mins

如何将 video $ video_duration 的格式从十进制更改为与 video $ video_begin video $ video_end 相同的格式:分钟:秒"(我不在乎日,月,年和小时)?

How do I change the format of video$video_duration from decimal to the same format as in video$video_begin and video$video_end: "Minutes:Seconds" (I don't care about day, month, year and hour)?

我尝试过:

video$video_duration <- as.POSIXct(video$video_duration, format = "%M:%S")

strptime(video$video_duration, format="%M:%S")

但是不...

我找到了一些答案,但我对它们并不满意:

I found some answers but I'm not very satisfied with them:

如何将小数转换为POSIX时间

将文本时间转换为十进制时间的算法

难道没有更多……方便且容易的方法吗?

Isn't there a more... handy and easier way to do it?

谢谢!

推荐答案

另一个选项:

library(lubridate)
video$video_duration <- as.numeric(video_end - video_begin, units = "secs")
video$video_duration  <- seconds_to_period(video$video_duration)

          video_begin           video_end video_duration
1 2017-09-12 00:08:14 2017-09-12 00:39:08        30M 54S
2 2017-09-12 00:04:47 2017-09-12 00:47:10        42M 23S
3 2017-09-12 00:08:27 2017-09-12 00:49:51        41M 24S
4 2017-09-12 00:04:59 2017-09-12 00:44:31        39M 32S
5 2017-09-12 00:04:57 2017-09-12 00:39:41        34M 44S
6 2017-09-12 00:07:51 2017-09-12 00:47:12        39M 21S
7 2017-09-12 00:06:11 2017-09-12 00:40:13         34M 2S
8 2017-09-12 00:05:30 2017-09-12 00:46:52        41M 22S

这篇关于如何将十进制时间转换为时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:33