Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

r - How to find an interval in csv datetime

I have a csv file with a datetime column

> head(GU$`Local time`)
[1] "2021-01-11 00:00:00 GMT" "2021-01-11 00:01:00 GMT"
[3] "2021-01-11 00:02:00 GMT" "2021-01-11 00:03:00 GMT"
[5] "2021-01-11 00:04:00 GMT" "2021-01-11 00:05:00 GMT"

And I want to create a boolean column returning TRUE if time is in a certain interval and FALSE otherwise .

I defined the start and end time :

StartPreLondonInterval <- as.POSIXct("05:05:00", "%H:%M:%S", tz = "Europe/London")
EndPreLondonInterval <-as.POSIXct("07:59:59", "%H:%M:%S", tz = "Europe/London")

But they return me not just the time, but the current day to, I want just the time :

> StartPreLondonInterval
[1] "2021-01-27 05:05:00 GMT"

Anyones now how can I do that ?

I was thinking that after the interval would be checked with interval() function from lubridate package .

question from:https://stackoverflow.com/questions/65925355/how-to-find-an-interval-in-csv-datetime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One possible solution is to use the format function to extract H:M:S from the datetime, then check if the H:M:S times are within a specified range.

# create dummy data
datetimes <- seq(from = as.POSIXct("2021-01-11 00:00:00", tz = "GMT"), length.out = 100, by = "mins")

Add hms and time_chk columns.

library(dplyr)

data.frame(local_time = datetimes) %>%
  mutate(hms = format(local_time, "%H:%M:%S"),
         time_chk = hms >= "00:01:00" & hms <= "00:03:00")


#---------
             local_time      hms time_chk
1   2021-01-11 00:00:00 00:00:00    FALSE
2   2021-01-11 00:01:00 00:01:00     TRUE
3   2021-01-11 00:02:00 00:02:00     TRUE
4   2021-01-11 00:03:00 00:03:00     TRUE
5   2021-01-11 00:04:00 00:04:00    FALSE
6   2021-01-11 00:05:00 00:05:00    FALSE
7   2021-01-11 00:06:00 00:06:00    FALSE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...