【问题标题】:How to convert a character date into POSIX time without loss in precision如何在不损失精度的情况下将字符日期转换为 POSIX 时间
【发布时间】:2014-02-06 10:18:22
【问题描述】:

我有以下日期,我想将其转换为 POSIX 时间。我关注了this answer,但如果我将日期转换回来,输入日期和输出日期会有所不同。

char_date <- "2012-04-27T20:48:14"
unix_date <- as.integer(as.POSIXct(char_date, origin="1970-01-01"))
unix_date
# [1] 1335448800

翻译回 2012 年 4 月 26 日星期四 14:00:00。

我在搞砸什么?

【问题讨论】:

  • 你在哪个时区?
  • 澳大利亚悉尼。但时间戳是在中欧拍摄的

标签: r date posixct


【解决方案1】:

不需要sub,您应该始终定义时区:

x <- as.POSIXct("2012-04-27T20:48:14", format="%Y-%m-%dT%H:%M:%S", tz="CET")
#[1] "2012-04-27 20:48:14 CEST"
as.numeric(x)
#[1] 1335552494

【讨论】:

    【解决方案2】:

    我认为这里有 2 个问题:T 字符正在影响字符解析器,因此它忽略了时间部分,我假设您的时区是 UTC+10,这就是为什么您的翻译是在上一个下午 2 点天。

    (as.POSIXct(char_date, origin="1970-01-01"))
    [1] "2012-04-27 BST"
    
    (as.POSIXct(sub("T"," ",char_date), origin="1970-01-01"))
    [1] "2012-04-27 20:48:14 BST"
    

    【讨论】:

    • 我应该注明时间戳的拍摄时间还是我的时间? (as.POSIXct(sub("T"," ",char_date), origin="1970-01-01", tz="CET"))?
    • @CptNemo 看你怎么想,但如果你不给,它会假定你机器的本地时区,所以你需要保持一致。
    猜你喜欢
    • 2019-10-08
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多