从日期时间变量中提取年份

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

Extracting year from date time variable

问题

I would only like to extract '2021' from this.

By the way, the class for this variable is 'character'.

英文:

I have some date/times in a variable where I would only like to extract the year.

Here is an example:

2/14/21 4:55

I would only like to extract '2021' from this.

By the way, the class for this variable is 'character'.

> class(df$DTS)
[1] "character"

答案1

得分: 2

以下是一个基本的R解决方案:

as.numeric(format(as.POSIXct("2/10/21 6:55", format = "%m/%d/%y %H:%M"), "%Y"))

[1] 2021


<details>
<summary>英文:</summary>

Here is a base R solution: 

as.numeric(format(as.POSIXct("2/10/21 6:55", format = "%m/%d/%y %H:%M"), "%Y"))

[1] 2021



</details>



# 答案2
**得分**: 1

library(lubridate)
"2/10/21 6:55" |> mdy_hm() |> year()

[1] 2021


<details>
<summary>英文:</summary>

library(lubridate)
"2/10/21 6:55" |> mdy_hm() |> year()

[1] 2021


</details>



huangapple
  • 本文由 发表于 2023年5月23日 01:01:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308448.html
匿名

发表评论

匿名网友

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

确定