简体   繁体   English

如何将 R 数据帧中的时间戳转换为日期

[英]How to convert timestamps within a R dataframe to date

I have a R data frame with multiple columns with one of which containing a timestamp.我有一个包含多列的 R 数据框,其中一列包含时间戳。

df <- data.frame(id=c(1:4), timestamp=c(123513,2,3,4))

The problem I have is trying to convert the timestamp say 123513 (integer) into a date ("1970-01-02").我遇到的问题是试图将时间戳说 123513(整数)转换为日期(“1970-01-02”)。

I have a function as below, that I wish to apply to all timestamps.我有一个如下功能,我希望将其应用于所有时间戳。

timestamp_to_date <- function(timestamp) {
    return (as.Date(as.POSIXct(timestamp, origin="1970-01-01", tz="Australia/Melbourne")))
}

As the other have mentioned, this should just work:正如其他人所提到的,这应该可以正常工作:

df <- data.frame(id=c(1:4), timestamp=c(123513,2,3,4))

timestamp_to_date <- function(timestamp) {
  return (as.Date(as.POSIXct(timestamp, origin="1970-01-01", tz="Australia/Melbourne")))
}

df$timestamp = timestamp_to_date(df$timestamp)

> df
  id  timestamp
1  1 1970-01-02
2  2 1970-01-01
3  3 1970-01-01
4  4 1970-01-01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM