从?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位数)
我有没有看到这个解释?
对此的简短回答是如何以科学格式打印数字
为了看到这个,我们可以设置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 question和this 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)
,或者在进入查询时用qerxswpoi右键填充qerxswpoi。