本文介绍了更改POSIXlt对象中元素的顺序并保留类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设

x <- "2012-10-07"

我在其中将其转换为POSIXlt

where I convert it to POSIXlt using

y <- strptime(x, format = "%Y-%m-%d")

我需要使用

z <- strftime(y, format = "%d/%m/%Y", tz = "GMT")

但是,这使对象成为字符.

However this makes the object a character.

class(z)
[1] "character"

以及何时

as.POSIXlt(z, format = "%d/%m/%Y", tz = "GMT")

打印结果为

[1] "2012-10-07 GMT"

(但希望使用%d/%m/%Y 的格式).

(but would expect it in the format of %d/%m/%Y).

是否有一种方法可以将 z 转换为 POSIXlt / POSIXct 对象并保留(打印)顺序%d/%m/%Y ?既然这个时间"对象知道日,月和年在哪里,而其他所有东西都只用于(漂亮)打印,那该不该担心呢?

Is there a way to convert z to POSIXlt/POSIXct object and preserve the (printing) order %d/%m/%Y? Should one even concern with this, since a "time" object knows where day, month and year are, and everything else is just for (pretty)printing?

推荐答案

类似以下内容:

x <- "2012-10-07"
y <- strptime(x, format = "%Y-%m-%d")

class(y) <- c("EUtime", class(y))

print.EUtime <- function (x, format="%d/%m/%Y %H:%M:%S", ...)
{
  max.print <- getOption("max.print", 9999L)
  if (max.print < length(x)) {
    print(format(x[seq_len(max.print)], format = format, usetz = TRUE), ...)
    cat(" [ reached getOption(\"max.print\") -- omitted",
        length(x) - max.print, "entries ]\n")
  }
  else print(format(x, format = format, usetz = TRUE), ...)
  invisible(x)
}

y
#[1] "07/10/2012 00:00:00 CEST"

我确定您可以自行修改此设置,使其仅输出午夜的日期.

I'm sure you can modify this yourself to only output the date for midnight.

这篇关于更改POSIXlt对象中元素的顺序并保留类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 11:07