英文:
Extract time out of a date and timestamp
问题
"我有一个时间戳的向量,只想提取出小时和分钟,例如我所拥有的看起来像是;2023-03-06T18:43:52+00:00,我想要它变成的是18:43,如果可能的话。我考虑过将它拆分并删除T和+之前和之后的所有内容(包括它们),但不太确定如何在使用gsub时完成这个操作,这也会保留我不想要的秒数。
tstamps
"2023-03-06T18:43:52+00:00" "2023-03-06T18:44:45.547+00:00" "2023-03-06T18:47:04.643+00:00""
英文:
I have a vector of timestamps and just wish to get the hour and minute out, for example what I have looks like; 2023-03-06T18:43:52+00:00 and what I want it to become is 18:43 if possible. I thought about splitting it up and removing everything before and after the T and + (inclusive) but wasnt quite sure how that was done using a gsub, this would also still leave the seconds which i dont want here
tstamps
"2023-03-06T18:43:52+00:00" "2023-03-06T18:44:45.547+00:00" "2023-03-06T18:47:04.643+00:00"
答案1
得分: 2
Sure, here's the translated code portion:
你可以使用 lubridate 和 dplyr 包来实现这个功能:
library(dplyr)
library(lubridate)
df <- data.frame(datetime = c("2023-03-06T18:43:52+00:00", "2023-03-06T12:30:00+00:00"))
df <- df %>%
mutate(time = format(ymd_hms(datetime), "%H:%M"))
df
The code remains the same, but it's now in Chinese.
英文:
you can use lubridate and dplyr packages for that:
library(dplyr)
library(lubridate)
df <- data.frame(datetime = c("2023-03-06T18:43:52+00:00", "2023-03-06T12:30:00+00:00"))
df <- df %>%
mutate(time = format(ymd_hms(datetime), "%H:%M"))
df
which will return:
datetime time
1 2023-03-06T18:43:52+00:00 18:43
2 2023-03-06T12:30:00+00:00 12:30
答案2
得分: 0
在删除偏移中的冒号后,我们可以使用strptime()
。
strftime(strptime(sub('(.+):(.+)', '\\', x), '%FT%H:%M:%OS%z', tz='GMT'), '%H:%M')
# [1] "18:43" "18:44" "18:47"
数据:
x <- c('2023-03-06T18:43:52+00:00', '2023-03-06T18:44:45.547+00:00', '2023-03-06T18:47:04.643+00:00')
英文:
After sub
away the colons in offset, we can use strptime()
.
strftime(strptime(sub('(.*):(.*)', '\\', x), '%FT%H:%M:%OS%z', tz='GMT'), '%H:%M')
# [1] "18:43" "18:44" "18:47"
Data:
x <- c('2023-03-06T18:43:52+00:00', '2023-03-06T18:44:45.547+00:00', '2023-03-06T18:47:04.643+00:00')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论