【问题标题】:r - converting POSIXct to millisecondsr - 将 POSIXct 转换为毫秒
【发布时间】:2016-04-12 03:04:11
【问题描述】:

?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 位数字)

是否有对此我没有看到的解释?

【问题讨论】:

  • 看看lapply(c(11,12,13), function(x) d[nchar(d*1000) %in% x] ),看看返回值的最后4位、3位和2位。
  • 还要考虑lapply(c(10e5, 10e6, 10e7), nchar)
  • @thelatemail - 谢谢,我明白你在说什么。但是,我仍然不完全理解发生了什么(或者可能更准确地说是为什么):)
  • 尾随零?太大而无法存储为整数,因此它是 sci 表示法和 pacman 吃掉的尾随零
  • @thelatemail - 所以它会出现 - 例如floor( log10 (d * 1000)) + 1

标签: r posixct


【解决方案1】:

总结答案

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

要看到这一点,我们可以设置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

【讨论】:

  • 如果你正在写一个包注释,你不能只把options(...)放在包的顶部,你必须把它放在一个函数中。
猜你喜欢
  • 2011-01-28
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2013-06-23
  • 2011-02-13
相关资源
最近更新 更多