Movatterモバイル変換


[0]ホーム

URL:


rdrr.io

DateTimeClasses: Date-Time Classes

DateTimeClassesR Documentation

Date-Time Classes

Description

Description of the classes"POSIXlt" and"POSIXct"representing calendar dates and times.

Usage

## S3 method for class 'POSIXct'print(x, tz = "", usetz = TRUE, max = NULL, ...)## S3 method for class 'POSIXct'summary(object, digits = 15, ...)time + zz + timetime - ztime1 lop time2

Arguments

x, object

an object to be printed or summarized from one of thedate-time classes.

tz, usetz

for timezone formatting, passed toformat.POSIXct.

max

numeric orNULL, specifying the maximal number ofentries to be printed. By default, whenNULL,getOption("max.print") used.

digits

number of significant digits for the computations:should be high enough to represent the least important time unitexactly.

...

further arguments to be passed from or to other methods.

time

date-time objects

time1, time2

date-time objects or character vectors. (Charactervectors are converted byas.POSIXct.)

z

a numeric vector (in seconds)

lop

one of==,!=,<,<=,>or>=.

Details

There are two basic classes of date/times. Class"POSIXct"represents the (signed) number of seconds since the beginning of 1970(in the UTC time zone) as a numeric vector. Class"POSIXlt" isa named list of vectors representing

sec

0–61: seconds.

min

0–59: minutes.

hour

0–23: hours.

mday

1–31: day of the month

mon

0–11: months after the first of the year.

year

years since 1900.

wday

0–6 day of the week, starting on Sunday.

yday

0–365: day of the year (365 only in leap years).

isdst

Daylight Saving Time flag. Positive if inforce, zero if not, negative if unknown.

zone

(Optional.) The abbreviation for the time zone inforce at that time:"" if unknown (but"" might alsobe used for UTC).

gmtoff

(Optional.) The offset in seconds from GMT:positive values are East of the meridian. UsuallyNA ifunknown, but0 could mean unknown.

(The last two components are not present for times in UTC and areplatform-dependent: they are supported on platforms based on BSD orglibc (including Linux and macOS) and those using thetzcode implementation shipped withR (including Windows). Butthey are not necessarily set.). Note that the internal list structureis somewhat hidden, as many methods (includinglength(x),print() andstr)apply to the abstract date-time vector, as for"POSIXct". AsfromR 3.5.0, one can extract and replacesingle componentsvia[ indexing with two indices (see the examples). Theclasses correspond to the POSIX/C99 constructs of ‘calendartime’ (thetime_t data type) and ‘local time’ (orbroken-down time, thestruct tm data type), from which theyalso inherit their names. The components of"POSIXlt" areinteger vectors, exceptsec andzone.

"POSIXct" is more convenient for including in data frames, and"POSIXlt" is closer to human-readable forms. A virtual class"POSIXt" exists from which both of the classes inherit: it isused to allow operations such as subtraction to mix the two classes.

Componentswday andyday of"POSIXlt" are forinformation, and are not used in the conversion to calendar time.However,isdst is needed to distinguish times at the end ofDST: typically 1am to 2am occurs twice, first in DST and then instandard time. At all other timesisdst can be deduced fromthe first six values, but the behaviour if it is set incorrectly isplatform-dependent.

Logical comparisons and some arithmetic operations are available forboth classes. One can add or subtract a number of seconds from adate-time object, but not add two date-time objects. Subtraction oftwo date-time objects is equivalent to usingdifftime.Be aware that"POSIXlt" objects will be interpreted as being inthe current time zone for these operations unless a time zone has beenspecified.

"POSIXlt" objects will often have an attribute"tzone",a character vector of length 3 giving the time zone name (from theTZenvironment variable or argumenttz of functions creating"POSIXlt" objects;"" marks the current time zone)and the names of the base time zoneand the alternate (daylight-saving) time zone. Sometimes this mayjust be of length one, giving the time zone name.

"POSIXct" objects may also have an attribute"tzone", acharacter vector of length one. If set to a non-empty value, it willdetermine how the object is converted to class"POSIXlt" and inparticular how it is printed. This is usually desirable, but if youwant to specify an object in a particular time zone but to be printedin the current time zone you may want to remove the"tzone"attribute (e.g., byc(x)).

Unfortunately, the conversion is complicated by the operation of timezones and leap seconds (according to this version ofR's data,\Sexpr{length(.leap.seconds)} days have been 86401 seconds long sofar, the last being on (actually, immediately before)\Sexpr{format(as.Date(utils::tail(.leap.seconds, 1)))}: the times of theextra seconds are in the object.leap.seconds). The details ofthis are entrusted to the OS services where possible. It seems thatsome rare systems used to use leap seconds, but all known currentplatforms ignore them (as required by POSIX). This is detected andcorrected for at build time, so"POSIXct" times used byR donot include leap seconds on any platform.

Usingc on"POSIXlt" objects converts them to thecurrent time zone, and on"POSIXct" objects drops any"tzone" attributes, unless they are all marked with the sametime zone.

A few times have specific issues. First, the leap seconds are ignored,and real times such as"2005-12-31 23:59:60" are (probably)treated as the next second. However, they will never be generated byR, and are unlikely to arise as input. Second, on some OSes there isa problem in the POSIX/C99 standard with"1969-12-31 23:59:59 UTC",which is-1 in calendar time and that value is on those OSesalso used as an error code. Thusas.POSIXct("1969-12-31 23:59:59", format = "%Y-%m-%d %H:%M:%S", tz = "UTC") may giveNA, and henceas.POSIXct("1969-12-31 23:59:59", tz = "UTC") will give"1969-12-31 23:59:00". Other OSes(including the code used byR on Windows) report errors separatelyand so are able to handle that time as valid.

The print methods respectoptions("max.print").

Sub-second Accuracy

Classes"POSIXct" and"POSIXlt" are able to expressfractions of a second. (Conversion of fractions between the two formsmay not be exact, but will have better than microsecond accuracy.)

Fractional seconds are printed only ifoptions("digits.secs") is set: seestrftime.

Valid ranges for times

The"POSIXlt" class can represent a very wide range of times (upto billions of years), but such times can only be interpreted withreference to a time zone.

The concept of time zones was first adopted in the nineteenth century,and the Gregorian calendar was introduced in 1582 but not universallyadopted until 1927. OS services almost invariably assume theGregorian calendar and may assume that the time zone that was firstenacted for the location was in force before that date. (The earliestlegislated time zone seems to have been London on 1847-12-01.) SomeOSes assume the previous use of ‘local time’ based on thelongitude of a location within the time zone.

Most operating systems representPOSIXct times as C typelong. This means that on 32-bit OSes this covers the period1902 to 2037. On all known 64-bit platforms and for the code we useon 32-bit Windows, the range of representable times is billions ofyears: however, not all can convert correctly times before 1902 orafter 2037. A few benighted OSes used a unsigned type and so cannotrepresent times before 1970.

Where possible the platform limits are detected, and outsidethe limits we use our own C code. This uses the offset fromGMT in use either for 1902 (when there was no DST) or that predictedfor one of 2030 to 2037 (chosen so that the likely DST transition daysare Sundays), and uses the alternate (daylight-saving) time zone onlyifisdst is positive or (if-1) if DST was predicted tobe in operation in the 2030s on that day.

Note that there are places (e.g., Rome) whose offset from UTC variedin the years prior to 1902, and these will be handled correctly onlywhere there is OS support.

There is no reason to suppose that the DST rules will remain the samein the future, and indeed the US legislated in 2005 to change itsrules as from 2007, with a possible future reversion. So conversionsfor times more than a year or two ahead are speculative.

Warnings

Some Unix-like systems (especially Linux ones) do not have environmentvariableTZ set, yet have internal code that expects it (as doesPOSIX). We have tried to work around this, but if you get unexpectedresults try settingTZ. SeeSys.timezone forvalid settings.

Great care is needed when comparing objects of class"POSIXlt".Not only are components and attributes optional; several componentsmay have values meaning ‘not yet determined’ and the same timerepresented in different time zones will look quite different.

Currently theorder of the list components of"POSIXlt"objects must not be changed, as several C-based conversion methodsrely on the order for efficiency.

References

Ripley, B. D. and Hornik, K. (2001).“Date-time classes.”R News,1(2), 8–11.https://www.r-project.org/doc/Rnews/Rnews_2001-2.pdf.

See Also

Dates for dates without times.

as.POSIXct andas.POSIXlt for conversionbetween the classes.

strptime for conversion to and from characterrepresentations.

Sys.time for clock time as a"POSIXct" object.

difftime for time intervals.

cut.POSIXt,seq.POSIXt,round.POSIXt andtrunc.POSIXt for methodsfor these classes.

weekdays for convenience extraction functions.

Examples

(z <- Sys.time())             # the current date, as class "POSIXct"Sys.time() - 3600             # an hour agoas.POSIXlt(Sys.time(), "GMT") # the current time in GMTformat(.leap.seconds)         # the leap seconds in your time zoneprint(.leap.seconds, tz = "PST8PDT")  # and in Seattle's## look at *internal* representation of "POSIXlt" :leapS <- as.POSIXlt(.leap.seconds)names(leapS) ; is.list(leapS)## str() "too smart" -->  need unclass(.):utils::str(unclass(leapS), vec.len = 7)## Extracting *single* components of POSIXlt objects:leapS[1 : 5, "year"]##  length(.) <- n   now works for "POSIXct" and "POSIXlt" :for(lpS in list(.leap.seconds, leapS)) {    ls <- lpS; length(ls) <- 12    l2 <- lpS; length(l2) <- 5 + length(lpS)    stopifnot(exprs = {      ## length(.) <- * is compatible to subsetting/indexing:      identical(ls, lpS[seq_along(ls)])      identical(l2, lpS[seq_along(l2)])      ## has filled with NA's      is.na(l2[(length(lpS)+1):length(l2)])    })}

What can we improve?

R Package Documentation

Browse R Packages

We want your feedback!

Note that we can't provide technical support on individual packages. You should contact the package authors for that.

 
Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, readEmbedding Snippets.

Close

[8]ページ先頭

©2009-2026 Movatter.jp