首页 文章

r - 将POSIXct转换为毫秒

提问于
浏览
1

这可能是一个非常简单的问题,我忽略了显而易见的问题,但无论如何我都要问它

?POSIXct 我们知道

类“POSIXct”表示自1970年初(UTC时区)以来的(带符号)秒数作为数字向量 .

因此,我假设要以毫秒为单位获得 POSIXct 值,我们需要乘以 1000


考虑2015年12月的日子

## generate sequence of days in December 2015
d <- seq(as.POSIXct("2015-12-01"), as.POSIXct("2015-12-31"), by = 60*60*24)
#  [1] "2015-12-01 AEDT" "2015-12-02 AEDT" 
#  ...
# [29] "2015-12-29 AEDT" "2015-12-30 AEDT" "2015-12-31 AEDT"

将它们转换为整数

d <- as.integer(d)

我们看到每个整数都是 10 个数字

nchar(d)
# [1] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10

当乘以1000转换为毫秒时,我们得到

nchar(d * 1000)
# [1] 13 13 13 13 12 13 13 13 13 12 13 13 13 13 12 13 13 13 13 11 13 13 13 13 12 13 13 13 13 12 13

一些值只有11或12位数(而我认为将10位数乘以1000会增加3位数)

我有没有看到这个解释?

1 回答

  • 2

    总结答案

    对此的简短回答是如何以科学格式打印数字

    为了看到这个,我们可以设置 options(scipen=1000) ,我们得到预期的结果 .

    options(scipen=1000); 
    nchar(d*1000)
    # [1] 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13
    

    更长的答案

    此问题的背景来自尝试使用 library(mongolite) 中的日期范围查询 mongodb 数据库

    例如,this questionthis issue显示要查询它需要转换为 numberLong 的日期以使查询正常工作 .

    为了弄清楚这一点,以及我遇到的问题,请考虑这些数据和后续查询

    library(mongolite)
    
    df <- data.frame(date = as.POSIXct(c("2015-12-19","2015-12-20","2015-12-21")),
                     val = c(1,2,3))
    
    mongo <- mongo(collection = "test", db = "test", url = "mongodb://localhost")
    
    ## insert data into test database
    mongo$insert(df)
    
    ## querying the 19th December 2015 works as expected, because d is formatted with 13 digits
    d <- as.integer(as.POSIXct("2015-12-19")) * 1000
    q <- paste0('{"date" : {"$date" : { "$numberLong" : "', d,'" } } }')
    mongo$find(query = q)
    # 
    # Imported 1 records. Simplifying into dataframe...
    # date val
    # 1 2015-12-19   1
    
    ## the 20th December 2015 errors, as d is formatted with < 13 digits
    d <- as.integer(as.POSIXct(("2015-12-20"))) * 1000
    q <- paste0('{"date" : {"$date" : { "$numberLong" : "', d,'" } } }')
    mongo$find(query = q)
    #
    # Error: Invalid input string 1.45053e+12, looking for 11
    
    ## the 21st December 2015 works as expected because d is formatted with 13 digits.
    d <- as.integer(as.POSIXct("2015-12-21")) * 1000
    q <- paste0('{"date" : {"$date" : { "$numberLong" : "', d,'" } } }')
    mongo$find(query = q)
    #
    # Imported 1 records. Simplifying into dataframe...
    # date val
    # 1 2015-12-21   3
    
    ## cleanup 
    rm(mongo); gc()
    

    所以为了解决这个问题,我要么设置 options(scipen=1000) ,要么在进入查询时用__右边填充 d .

相关问题