时间如何取舍? [英] How to round a time?

查看:20
本文介绍了时间如何取舍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小时向量.例如:

I have a vector of hours. For example:

vec.hours <- c("15:52:00", "15:56:00", "12:10:00", "15:12:00",  "11:49:00" ,"13:35:00", "14:53:00")

我想将小时数四舍五入以获得最接近的整 5 分钟的新小时数,像这样.

I would like to round the hours to get the new hours that will be the nearest whole 5 minutes, like this.

round.hours <- c("15:50:00", "16:00:00", "12:10:00", "15:10:00",  "11:50:00" ,"13:35:00", "14:55:00" )

我试过了

hour <- strptime(vec.hours , "%H:%M:%S")
round.hour <- round(hour , "mins")

但它不起作用.

每轮之后我想做 +/- 一小时,例如这样:

After for each round.hours I want to do +/- one hour, for example like this:

hour.rd <- strptime(round.hours[1] , "%H:%M:%S")
hourM <- hour.rd - 3600
hourP <- hour.rd + 3600
l.tm <- timeSequence(from = hourM, to = hourP,format = "%H-%S-%M",by="5 min",FinCenter = "Europe/Zurich")

因此,对于 15:50:00,我有一个从 14:50 到 16:50 的时间向量.

so, for 15:50:00 I have a vector of times from 14:50 until 16:50.

我不知道如何从 vec.hours 获取 round.hour.

I dont know how to get round.hour from vec.hours.

非常感谢

推荐答案

我会将小时数放入 datetime 对象中,将它们转换为 POSIXlt,这允许您以整数形式访问分钟数,使用四舍五入整数除法,然后再次提取小时.

I would put the hours into datetime objects, convert these to POSIXlt, which allows you to access the minutes as integers, round using integer division, then extract the hours again.

timestamps <- as.POSIXlt(as.POSIXct('1900-1-1', tz='UTC') + as.difftime(vec.hours))
timestamps$min <- (timestamps$min + 5/2) %/% 5 * 5
format(timestamps, format='%H:%M:%S')
# [1] "15:50:00" "15:55:00" "12:10:00" "15:10:00" "11:50:00" "13:35:00" "14:55:00"

这篇关于时间如何取舍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆