日期时间

常用的日期与时间的class为:Date,POSIXlt和POSIXct; 常用的包:lubridate。

类 Class

Date类

只处理日期,不处理时间。 Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates.

POSIXlt和POSIXct

可以处理时间和日期,并且包含时区信息。

  • POSIXct格式的时间:以有符号整数形式存储,表示从1970-01-01到该时间点经过的秒数;
  • POSIXlt格式的时间:以字符串形式存储,包含年月日等。

There are two POSIXt types, POSIXct and POSIXlt.

  • "ct" can stand for calendar time, it stores the number of seconds since the origin.
  • "lt", or local time, keeps the date as a list of time attributes (such as "hour","min", "sec", "mon" etc).

POSIXct类型

  • 两个POSIXct类型的变量可以直接相减,用来计算时间差,有正负数之分;
  • 两个POSIXct类型的变量可以直接比较大小。

POSIXlt类型

对于POSIXlt类型的向量t,做循环的时候不能使用for (i in t),t中元素的每个值都会被拆分,需要使用下标

for ( i in 1 : length(t))
{ 
    t[i] ...
}

函数

as.Date()

将字符串转换为Date类 Functions to convert between character representations and objects of class "Date" representing calendar dates.

用法

  1. as.Date(x, ...)
  2. S3 method for class 'character':as.Date(x, format, ...)
  3. S3 method for class 'numeric':as.Date(x, origin, ...)
  4. S3 method for class 'POSIXct':as.Date(x, tz = "UTC", ...)

参数

  • x:An object to be converted.要被转换的对象;
  • format:
    • 字符串类型的日期格式; A character string.
    • 若没有指定,则默认为"%Y-%m-%d"或"%Y/%m/%d";
    • If not specified, it will try "%Y-%m-%d" then "%Y/%m/%d" on the first non-NA element, and give an error if neither works. Otherwise, the processing is via strptime.
  • origin:a Date object, or something which can be coerced by as.Date(origin, ...) to such an object.
    • 若origin参数被赋值,则x为一个数字,返回值为origin日期后x天的具体日期。
  • tz:a time zone name

strptime()

将字符串向量转换为POSIXlt类。 strptime() is a function to directly convert character vectors (of a variety of formats) to POSIXlt format.

用法

strptime(x, format, tz = "")

as.POSIXlt()

converts a variety of data types to POSIXlt. It tries to be intelligent and do the sensible thing - in the case of character, it acts as a wrapper to strptime.

as.POSIXct()

converts a variety of data types to POSIXct. It also tries to be intelligent and do the sensible thing - in the case of character, it runs strptime first, then does the conversion from POSIXlt to POSIXct.

It makes sense that strptime is faster, because strptime only handles character input whilst the others try to determine which method to use from input type. It should also be a bit safer in that being handed unexpected data would just give an error, instead of trying to do the intelligent thing that might not be what you want.

常用format(注意大小写):

  • %Y:年(包含century);
  • %y:年(不包含century,00-99);
  • %m:月;
  • %d:日;
  • %H:时;
  • %M:分;
  • %S:秒;

results matching ""

    No results matching ""