提取日期和时间戳中的时间。

huangapple go评论71阅读模式
英文:

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 &lt;- data.frame(datetime = c(&quot;2023-03-06T18:43:52+00:00&quot;, &quot;2023-03-06T12:30:00+00:00&quot;))

df &lt;- df %&gt;%
  mutate(time = format(ymd_hms(datetime), &quot;%H:%M&quot;))
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(&#39;(.*):(.*)&#39;, &#39;\\&#39;, x), &#39;%FT%H:%M:%OS%z&#39;, tz=&#39;GMT&#39;), &#39;%H:%M&#39;)
# [1] &quot;18:43&quot; &quot;18:44&quot; &quot;18:47&quot;

Data:

x &lt;- c(&#39;2023-03-06T18:43:52+00:00&#39;, &#39;2023-03-06T18:44:45.547+00:00&#39;, &#39;2023-03-06T18:47:04.643+00:00&#39;)

huangapple
  • 本文由 发表于 2023年4月1日 00:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定