简体   繁体   English

将 UNIX 时间戳转换为 R 中的 POSIXct

[英]Converting UNIX timestamp to POSIXct in R

I'm trying to convert a column from my hadoop data containing UNIX values (integer) to POSIXct format in R.我正在尝试将包含 UNIX 值(整数)的 hadoop 数据中的列转换为 R 中的 POSIXct 格式。 I am using the following code:我正在使用以下代码:

hadoop$time <- as.POSIXct(hadoop$time, origin="1970-01-01")

However, when I use as.POSIXct I get the following error:但是,当我使用 as.POSIXct 时,出现以下错误:

Error in as.POSIXct.default(hadoop$time, origin="1970-01-01") : do not know how to convert 'hadoop$time' to class "POSIXct" 

A sample of my column time values is this:我的列时间值示例如下:

integer64
    [1] 1606851081 1606851075 1606851065 1606850993 1606850976 1606823547

If I put one of these values through the Epoch date converter it returns a valid date time.如果我通过 Epoch 日期转换器输入这些值之一,它会返回一个有效的日期时间。 I have tried multiple solutions posted on here such as using the "as_datetime" function or the "anytime" package.我已经尝试过在此处发布的多种解决方案,例如使用“as_datetime”function 或“anytime”package。 Sample code:示例代码:

hadoop$time <- anytime(hadoop$time)
hadoop$time <- as_datetime(hadoop$time)

However these attempts have also been unsuccessful.然而,这些尝试也没有成功。 Not sure what I am doing wrong here, hope somebody can help me out.不知道我在这里做错了什么,希望有人可以帮助我。

Some added context: I am running this in a notebook in Databricks.一些附加的上下文:我在 Databricks 的笔记本中运行它。

There is no reproducible code so the answer will not provide working example as well.没有可重现的代码,因此答案也不会提供工作示例。 Converting UNIX epoch time to POSIXct is just changing its class attribute.将 UNIX 纪元时间转换为 POSIXct 只是更改其 class 属性。 Assuming origin 1970-01-01.假设起源 1970-01-01。

Therefore whatever class of UNIX epoch you have, just coerce it to numeric, and then as.POSIXct(num, origin="1970-01-01") .因此,无论您拥有 UNIX 时代的 class 什么,只需将其强制为数字,然后将其强制转换为as.POSIXct(num, origin="1970-01-01")

int64_epoch = bit64::as.integer64(1606851081)
num_epoch = as.numeric(int64_epoch)
as.POSIXct(num_epoch, origin="1970-01-01")
#[1] "2020-12-01 21:31:21 EET"

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

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