Title: | Make Dealing with Dates a Little Easier |
---|---|
Description: | Functions to work with date-times and time-spans: fast and user friendly parsing of date-time data, extraction and updating of components of a date-time (years, months, days, hours, minutes, and seconds), algebraic manipulation on date-time and time-span objects. The 'lubridate' package has a consistent and memorable syntax that makes working with dates easy and fun. |
Authors: | Vitalie Spinu [aut, cre], Garrett Grolemund [aut], Hadley Wickham [aut], Davis Vaughan [ctb], Ian Lyttle [ctb], Imanuel Costigan [ctb], Jason Law [ctb], Doug Mitarotonda [ctb], Joseph Larmarange [ctb], Jonathan Boiser [ctb], Chel Hee Lee [ctb] |
Maintainer: | Vitalie Spinu <[email protected]> |
License: | GPL (>= 2) |
Version: | 1.9.3.9000 |
Built: | 2024-10-28 05:36:19 UTC |
Source: | https://github.com/tidyverse/lubridate |
Adding months frustrates basic arithmetic because consecutive months have
different lengths. With other elements, it is helpful for arithmetic to
perform automatic roll over. For example, 12:00:00 + 61 seconds becomes
12:01:01. However, people often prefer that this behavior NOT occur with
months. For example, we sometimes want January 31 + 1 month = February 28 and
not March 3. %m+%
performs this type of arithmetic. Date %m+%
months(n)
always returns a date in the nth month after Date. If the new date would
usually spill over into the n + 1th month, %m+%
will return the last day of
the nth month (rollback()
). Date %m-%
months(n) always returns a
date in the nth month before Date.
e1 %m+% e2 add_with_rollback(e1, e2, roll_to_first = FALSE, preserve_hms = TRUE)
e1 %m+% e2 add_with_rollback(e1, e2, roll_to_first = FALSE, preserve_hms = TRUE)
e1 |
A period or a date-time object of class POSIXlt, POSIXct or Date. |
e2 |
A period or a date-time object of class POSIXlt, POSIXct or Date. Note that one of e1 and e2 must be a period and the other a date-time object. |
roll_to_first |
rollback to the first day of the month instead of the
last day of the previous month (passed to |
preserve_hms |
retains the same hour, minute, and second information? If
FALSE, the new date will be at 00:00:00 (passed to |
%m+%
and %m-%
handle periods with components less than a month by first
adding/subtracting months and then performing usual arithmetics with smaller
units.
%m+%
and %m-%
should be used with caution as they are not one-to-one
operations and results for either will be sensitive to the order of
operations.
A date-time object of class POSIXlt, POSIXct or Date
jan <- ymd_hms("2010-01-31 03:04:05") jan + months(1:3) # Feb 31 and April 31 returned as NA # NA "2010-03-31 03:04:05 UTC" NA jan %m+% months(1:3) # No rollover leap <- ymd("2012-02-29") "2012-02-29 UTC" leap %m+% years(1) leap %m+% years(-1) leap %m-% years(1) x <- ymd_hms("2019-01-29 01:02:03") add_with_rollback(x, months(1)) add_with_rollback(x, months(1), preserve_hms = FALSE) add_with_rollback(x, months(1), roll_to_first = TRUE) add_with_rollback(x, months(1), roll_to_first = TRUE, preserve_hms = FALSE)
jan <- ymd_hms("2010-01-31 03:04:05") jan + months(1:3) # Feb 31 and April 31 returned as NA # NA "2010-03-31 03:04:05 UTC" NA jan %m+% months(1:3) # No rollover leap <- ymd("2012-02-29") "2012-02-29 UTC" leap %m+% years(1) leap %m+% years(-1) leap %m-% years(1) x <- ymd_hms("2019-01-29 01:02:03") add_with_rollback(x, months(1)) add_with_rollback(x, months(1), preserve_hms = FALSE) add_with_rollback(x, months(1), roll_to_first = TRUE) add_with_rollback(x, months(1), roll_to_first = TRUE, preserve_hms = FALSE)
Check whether a
lies within the interval b
, inclusive of the endpoints.
a %within% b
a %within% b
a |
An interval or date-time object. |
b |
Either an interval vector, or a list of intervals. If |
A logical vector.
int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-01-01")) ymd("2001-05-03") %within% int # TRUE int2 %within% int # TRUE ymd("1999-01-01") %within% int # FALSE ## recycling (carefully note the difference between using a vector of ## intervals and list of intervals for the second argument) dates <- ymd(c("2014-12-20", "2014-12-30", "2015-01-01", "2015-01-03")) blackout_vector <- c( interval(ymd("2014-12-30"), ymd("2014-12-31")), interval(ymd("2014-12-30"), ymd("2015-01-03")) ) dates %within% blackout_vector ## within ANY of the intervals of a list dates <- ymd(c("2014-12-20", "2014-12-30", "2015-01-01", "2015-01-03")) lst <- list( interval(ymd("2014-12-30"), ymd("2014-12-31")), interval(ymd("2014-12-30"), ymd("2015-01-03")) ) dates %within% lst ## interval within a list of intervals int <- interval( ymd("2014-12-20", "2014-12-30"), ymd("2015-01-01", "2015-01-03") ) int %within% lst
int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-01-01")) ymd("2001-05-03") %within% int # TRUE int2 %within% int # TRUE ymd("1999-01-01") %within% int # FALSE ## recycling (carefully note the difference between using a vector of ## intervals and list of intervals for the second argument) dates <- ymd(c("2014-12-20", "2014-12-30", "2015-01-01", "2015-01-03")) blackout_vector <- c( interval(ymd("2014-12-30"), ymd("2014-12-31")), interval(ymd("2014-12-30"), ymd("2015-01-03")) ) dates %within% blackout_vector ## within ANY of the intervals of a list dates <- ymd(c("2014-12-20", "2014-12-30", "2015-01-01", "2015-01-03")) lst <- list( interval(ymd("2014-12-30"), ymd("2014-12-31")), interval(ymd("2014-12-30"), ymd("2015-01-03")) ) dates %within% lst ## interval within a list of intervals int <- interval( ymd("2014-12-20", "2014-12-30"), ymd("2015-01-01", "2015-01-03") ) int %within% lst
Does date time occur in the am or pm?
am(x) pm(x)
am(x) pm(x)
x |
a date-time object |
TRUE or FALSE depending on whether x occurs in the am or pm
x <- ymd("2012-03-26") am(x) pm(x)
x <- ymd("2012-03-26") am(x) pm(x)
Convert an object to a date or date-time
as_date(x, ...) ## S4 method for signature 'ANY' as_date(x, ...) ## S4 method for signature 'POSIXt' as_date(x, tz = NULL) ## S4 method for signature 'numeric' as_date(x, origin = lubridate::origin) ## S4 method for signature 'character' as_date(x, tz = NULL, format = NULL) as_datetime(x, ...) ## S4 method for signature 'ANY' as_datetime(x, tz = lubridate::tz(x)) ## S4 method for signature 'POSIXt' as_datetime(x, tz = lubridate::tz(x)) ## S4 method for signature 'numeric' as_datetime(x, origin = lubridate::origin, tz = "UTC") ## S4 method for signature 'character' as_datetime(x, tz = "UTC", format = NULL) ## S4 method for signature 'Date' as_datetime(x, tz = "UTC")
as_date(x, ...) ## S4 method for signature 'ANY' as_date(x, ...) ## S4 method for signature 'POSIXt' as_date(x, tz = NULL) ## S4 method for signature 'numeric' as_date(x, origin = lubridate::origin) ## S4 method for signature 'character' as_date(x, tz = NULL, format = NULL) as_datetime(x, ...) ## S4 method for signature 'ANY' as_datetime(x, tz = lubridate::tz(x)) ## S4 method for signature 'POSIXt' as_datetime(x, tz = lubridate::tz(x)) ## S4 method for signature 'numeric' as_datetime(x, origin = lubridate::origin, tz = "UTC") ## S4 method for signature 'character' as_datetime(x, tz = "UTC", format = NULL) ## S4 method for signature 'Date' as_datetime(x, tz = "UTC")
x |
a vector of POSIXt, numeric or character objects |
... |
further arguments to be passed to specific methods (see above). |
tz |
a time zone name (default: time zone of the POSIXt object |
origin |
a Date object, or something which can be coerced by |
format |
format argument for character methods. When supplied parsing is
performed by |
a vector of Date objects corresponding to x
.
These are drop in replacements for as.Date()
and as.POSIXct()
, with a few
tweaks to make them work more intuitively.
Called on a POSIXct
object, as_date()
uses the tzone attribute of
the object to return the same date as indicated by the printed representation
of the object. This differs from as.Date, which ignores the attribute and
uses only the tz argument to as.Date()
("UTC" by default).
Both functions provide a default origin argument for numeric vectors.
Both functions will generate NAs for invalid date format. Valid formats are those described by ISO8601 standard. A warning message will provide a count of the elements that were not converted.
as_datetime()
defaults to using UTC.
dt_utc <- ymd_hms("2010-08-03 00:50:50") dt_europe <- ymd_hms("2010-08-03 00:50:50", tz = "Europe/London") c(as_date(dt_utc), as.Date(dt_utc)) c(as_date(dt_europe), as.Date(dt_europe)) ## need not supply origin as_date(10) ## Will replace invalid date format with NA dt_wrong <- c("2009-09-29", "2012-11-29", "2015-29-12") as_date(dt_wrong)
dt_utc <- ymd_hms("2010-08-03 00:50:50") dt_europe <- ymd_hms("2010-08-03 00:50:50", tz = "Europe/London") c(as_date(dt_utc), as.Date(dt_utc)) c(as_date(dt_europe), as.Date(dt_europe)) ## need not supply origin as_date(10) ## Will replace invalid date format with NA dt_wrong <- c("2009-09-29", "2012-11-29", "2015-29-12") as_date(dt_wrong)
as.duration changes Interval, Period and numeric class objects to Duration objects. Numeric objects are changed to Duration objects with the seconds unit equal to the numeric value.
as.duration(x, ...)
as.duration(x, ...)
x |
Object to be coerced to a duration |
... |
Parameters passed to other methods. Currently unused. |
Durations are exact time measurements, whereas periods are relative time
measurements. See Period. The length of a period depends
on when it occurs. Hence, a one to one mapping does not exist between
durations and periods. When used with a period object, as.duration provides
an inexact estimate of the length of the period; each time unit is assigned
its most common number of seconds. A period of one month is converted to
2628000 seconds (approximately 30.42 days). This ensures that 12 months will
sum to 365 days, or one normal year. For an exact transformation, first
transform the period to an interval with as.interval()
.
A duration object
span <- interval(ymd("2009-01-01"), ymd("2009-08-01")) # interval as.duration(span) as.duration(10) # numeric dur <- duration(hours = 10, minutes = 6) as.numeric(dur, "hours") as.numeric(dur, "minutes")
span <- interval(ymd("2009-01-01"), ymd("2009-08-01")) # interval as.duration(span) as.duration(10) # numeric dur <- duration(hours = 10, minutes = 6) as.numeric(dur, "hours") as.numeric(dur, "minutes")
interval
as.interval changes difftime, Duration, Period and numeric class objects to intervals that begin at the specified date-time. Numeric objects are first coerced to timespans equal to the numeric value in seconds.
as.interval(x, start, ...)
as.interval(x, start, ...)
x |
a duration, difftime, period, or numeric object that describes the length of the interval |
start |
a POSIXt or Date object that describes when the interval begins |
... |
additional arguments to pass to as.interval |
as.interval can be used to create accurate transformations between Period
objects, which measure time spans in variable length units, and Duration objects,
which measure timespans as an exact number of seconds. A start date-
time must be supplied to make the conversion. Lubridate uses
this start date to look up how many seconds each variable
length unit (e.g. month, year) lasted for during the time span
described. See
as.duration()
, as.period()
.
an interval object
diff <- make_difftime(days = 31) # difftime as.interval(diff, ymd("2009-01-01")) as.interval(diff, ymd("2009-02-01")) dur <- duration(days = 31) # duration as.interval(dur, ymd("2009-01-01")) as.interval(dur, ymd("2009-02-01")) per <- period(months = 1) # period as.interval(per, ymd("2009-01-01")) as.interval(per, ymd("2009-02-01")) as.interval(3600, ymd("2009-01-01")) # numeric
diff <- make_difftime(days = 31) # difftime as.interval(diff, ymd("2009-01-01")) as.interval(diff, ymd("2009-02-01")) dur <- duration(days = 31) # duration as.interval(dur, ymd("2009-01-01")) as.interval(dur, ymd("2009-02-01")) per <- period(months = 1) # period as.interval(per, ymd("2009-01-01")) as.interval(per, ymd("2009-02-01")) as.interval(3600, ymd("2009-01-01")) # numeric
as.period changes Interval, Duration, difftime and numeric class objects to Period class objects with the specified units.
as.period(x, unit, ...)
as.period(x, unit, ...)
x |
an interval, difftime, or numeric object |
unit |
A character string that specifies which time units to build period in. unit is only implemented for the as.period.numeric method and the as.period.interval method. For as.period.interval, as.period will convert intervals to units no larger than the specified unit. |
... |
additional arguments to pass to as.period |
Users must specify which time units to measure the period in. The exact length of
each time unit in a period will depend on when it occurs. See
Period and period()
.
The choice of units is not trivial; units that are
normally equal may differ in length depending on when the time period
occurs. For example, when a leap second occurs one minute is longer than 60
seconds.
Because periods do not have a fixed length, they can not be accurately
converted to and from Duration objects. Duration objects measure time spans
in exact numbers of seconds, see Duration. Hence, a one to one
mapping does not exist between durations and periods. When used with a
Duration object, as.period provides an inexact estimate; the duration is
broken into time units based on the most common lengths of time units, in
seconds. Because the length of months are particularly variable, a period
with a months unit can not be coerced from a duration object. For an exact
transformation, first transform the duration to an interval with
as.interval()
.
Coercing an interval to a period may cause surprising behavior if you request periods with small units. A leap year is 366 days long, but one year long. Such an interval will convert to 366 days when unit is set to days and 1 year when unit is set to years. Adding 366 days to a date will often give a different result than adding one year. Daylight savings is the one exception where this does not apply. Interval lengths are calculated on the UTC timeline, which does not use daylight savings. Hence, periods converted with seconds or minutes will not reflect the actual variation in seconds and minutes that occurs due to daylight savings. These periods will show the "naive" change in seconds and minutes that is suggested by the differences in clock time. See the examples below.
a period object
span <- interval(ymd_hms("2009-01-01 00:00:00"), ymd_hms("2010-02-02 01:01:01")) # interval as.period(span) as.period(span, unit = "day") "397d 1H 1M 1S" leap <- interval(ymd("2016-01-01"), ymd("2017-01-01")) as.period(leap, unit = "days") as.period(leap, unit = "years") dst <- interval( ymd("2016-11-06", tz = "America/Chicago"), ymd("2016-11-07", tz = "America/Chicago") ) # as.period(dst, unit = "seconds") as.period(dst, unit = "hours") per <- period(hours = 10, minutes = 6) as.numeric(per, "hours") as.numeric(per, "minutes")
span <- interval(ymd_hms("2009-01-01 00:00:00"), ymd_hms("2010-02-02 01:01:01")) # interval as.period(span) as.period(span, unit = "day") "397d 1H 1M 1S" leap <- interval(ymd("2016-01-01"), ymd("2017-01-01")) as.period(leap, unit = "days") as.period(leap, unit = "years") dst <- interval( ymd("2016-11-06", tz = "America/Chicago"), ymd("2016-11-07", tz = "America/Chicago") ) # as.period(dst, unit = "seconds") as.period(dst, unit = "hours") per <- period(hours = 10, minutes = 6) as.numeric(per, "hours") as.numeric(per, "minutes")
Encode a date-time object into a cyclic coordinate system in which the distances between two pairs of dates separated by the same time duration are the same.
cyclic_encoding( x, periods, encoders = c("sin", "cos"), week_start = getOption("lubridate.week.start", 7) )
cyclic_encoding( x, periods, encoders = c("sin", "cos"), week_start = getOption("lubridate.week.start", 7) )
x |
a date-time object |
periods |
a character vector of periods. Follows same specification as period and floor_date functions. |
encoders |
names of functions to produce the encoding. Defaults to "sin" and "cos". Names of any predefined functions accepting a numeric input are allowed. |
week_start |
week start day (Default is 7, Sunday. Set |
Machine learning models don't know that December 31st and January 1st are
close in our human calendar sense. cyclic_encoding
makes it obvious to the
machine learner that two calendar dates are close by mapping the dates onto
the circle.
a numeric matrix with number of columns equal length(periods) * length(types)
.
times <- ymd_hms("2019-01-01 00:00:00") + hours(0:23) cyclic_encoding(times, c("day", "week", "month")) plot(cyclic_encoding(times, "1d")) plot(cyclic_encoding(times, "2d"), xlim = c(-1, 1)) plot(cyclic_encoding(times, "4d"), xlim = c(-1, 1))
times <- ymd_hms("2019-01-01 00:00:00") + hours(0:23) cyclic_encoding(times, c("day", "week", "month")) plot(cyclic_encoding(times, "1d")) plot(cyclic_encoding(times, "2d"), xlim = c(-1, 1)) plot(cyclic_encoding(times, "4d"), xlim = c(-1, 1))
Date-time must be a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
date(x) date(x) <- value
date(x) date(x) <- value
x |
a date-time object |
value |
an object for which the |
date()
does not yet support years before 0 C.E.
Also date()
is not defined for Period objects.
the date of x as a Date
date()
can be called without any arguments to return a string representing
the current date-time. This provides compatiblity with base:date()
which
it overrides.
x <- ymd_hms("2012-03-26 23:12:13", tz = "America/New_York") date(x) as.Date(x) # by default as.Date assumes you want to know the date in UTC as.Date(x, tz = "America/New_York") date(x) <- as.Date("2000-01-02") x
x <- ymd_hms("2012-03-26 23:12:13", tz = "America/New_York") date(x) as.Date(x) # by default as.Date assumes you want to know the date in UTC as.Date(x, tz = "America/New_York") date(x) <- as.Date("2000-01-02") x
Converts a decimal to a date
date_decimal(decimal, tz = "UTC")
date_decimal(decimal, tz = "UTC")
decimal |
a numeric object |
tz |
the time zone required |
a POSIXct object, whose year corresponds to the integer part of decimal. The months, days, hours, minutes and seconds elements are picked so the date-time will accurately represent the fraction of the year expressed by decimal.
date <- ymd("2009-02-10") decimal <- decimal_date(date) # 2009.11 date_decimal(decimal) # "2009-02-10 UTC"
date <- ymd("2009-02-10") decimal <- decimal_date(date) # 2009.11 date_decimal(decimal) # "2009-02-10 UTC"
update.Date()
and update.POSIXt()
return a date with the specified
elements updated. Elements not specified will be left unaltered. update.Date
and update.POSIXt do not add the specified values to the existing date, they
substitute them for the appropriate parts of the existing date.
## S3 method for class 'POSIXt' update( object, ..., roll_dst = c("NA", "post"), week_start = getOption("lubridate.week.start", 7), roll = NULL, simple = NULL )
## S3 method for class 'POSIXt' update( object, ..., roll_dst = c("NA", "post"), week_start = getOption("lubridate.week.start", 7), roll = NULL, simple = NULL )
object |
a date-time object |
... |
named arguments: years, months, ydays, wdays, mdays, days, hours, minutes, seconds, tzs (time zone component) |
roll_dst |
is a string vector of length one or two. When two values are supplied they specify how to roll date-times when they fall into "skipped" and "repeated" DST transitions respectively. A single value is replicated to the length of two. Possible values are: * `pre` - Use the time before the transition boundary. * `boundary` - Use the time exactly at the boundary transition. * `post` - Use the time after the boundary transition. * `xfirst` - crossed-first: First time which occurred when crossing the boundary. For addition with positive units pre interval is crossed first and post interval last. With negative units post interval is crossed first, pre - last. For subtraction the logic is reversed. * `xlast` - crossed-last. * `NA` - Produce NAs when the resulting time falls inside the problematic interval. For example 'roll_dst = c("NA", "pre") indicates that for skiped intervals return NA and for repeated times return the earlier time. When multiple units are supplied the meaning of "negative period" is determined by
the largest unit. For example "xfirst" and "xlast" make sense for addition and subtraction only. An error is raised if an attempt is made to use them with other functions. |
week_start |
week start day (Default is 7, Sunday. Set |
simple , roll
|
deprecated |
a date object with the requested elements updated. The object will retain its original class unless an element is updated which the original class does not support. In this case, the date returned will be a POSIXlt date object.
date <- ymd("2009-02-10") update(date, year = 2010, month = 1, mday = 1) update(date, year = 2010, month = 13, mday = 1) update(date, minute = 10, second = 3)
date <- ymd("2009-02-10") update(date, year = 2010, month = 1, mday = 1) update(date, year = 2010, month = 13, mday = 1) update(date, minute = 10, second = 3)
Get/set days component of a date-time
day(x) mday(x) wday( x, label = FALSE, abbr = TRUE, week_start = getOption("lubridate.week.start", 7), locale = Sys.getlocale("LC_TIME") ) qday(x) yday(x) day(x) <- value mday(x) <- value qday(x) <- value qday(x) <- value wday(x, week_start = getOption("lubridate.week.start", 7)) <- value yday(x) <- value
day(x) mday(x) wday( x, label = FALSE, abbr = TRUE, week_start = getOption("lubridate.week.start", 7), locale = Sys.getlocale("LC_TIME") ) qday(x) yday(x) day(x) <- value mday(x) <- value qday(x) <- value qday(x) <- value wday(x, week_start = getOption("lubridate.week.start", 7)) <- value yday(x) <- value
x |
a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, or fts object. |
label |
logical. Only available for wday. TRUE will display the day of the week as an ordered factor of character strings, such as "Sunday." FALSE will display the day of the week as a number. |
abbr |
logical. Only available for wday. FALSE will display the day of the week as an ordered factor of character strings, such as "Sunday." TRUE will display an abbreviated version of the label, such as "Sun". abbr is disregarded if label = FALSE. |
week_start |
day on which week starts following ISO conventions: 1 means Monday
and 7 means Sunday (default). When |
locale |
locale to use for day names. Default to current locale. |
value |
(for |
mday()
and yday()
return the day of the month and day of the year
respectively. day()
and day<-()
are aliases for mday()
and mday<-()
.
wday()
returns the day of the week as a decimal number or an ordered factor
if label is TRUE
.
x <- as.Date("2009-09-02") wday(x) # 4 wday(x, label = TRUE) # Wed wday(x, week_start = 1) # 3 wday(x, week_start = 7) # 4 wday(x, label = TRUE, week_start = 7) # Wed (Sun is the first level) wday(x, label = TRUE, week_start = 1) # Wed (Mon is the first level) wday(ymd(080101)) wday(ymd(080101), label = TRUE, abbr = FALSE) wday(ymd(080101), label = TRUE, abbr = TRUE) wday(ymd(080101) + days(-2:4), label = TRUE, abbr = TRUE) x <- as.Date("2009-09-02") yday(x) # 245 mday(x) # 2 yday(x) <- 1 # "2009-01-01" yday(x) <- 366 # "2010-01-01" mday(x) > 3
x <- as.Date("2009-09-02") wday(x) # 4 wday(x, label = TRUE) # Wed wday(x, week_start = 1) # 3 wday(x, week_start = 7) # 4 wday(x, label = TRUE, week_start = 7) # Wed (Sun is the first level) wday(x, label = TRUE, week_start = 1) # Wed (Mon is the first level) wday(ymd(080101)) wday(ymd(080101), label = TRUE, abbr = FALSE) wday(ymd(080101), label = TRUE, abbr = TRUE) wday(ymd(080101) + days(-2:4), label = TRUE, abbr = TRUE) x <- as.Date("2009-09-02") yday(x) # 245 mday(x) # 2 yday(x) <- 1 # "2009-01-01" yday(x) <- 366 # "2010-01-01" mday(x) > 3
Date-time must be a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
days_in_month(x)
days_in_month(x)
x |
a date-time object |
An integer of the number of days in the month component of the date-time object.
Converts a date to a decimal of its year
decimal_date(date)
decimal_date(date)
date |
a POSIXt or Date object |
a numeric object where the date is expressed as a fraction of its year
date <- ymd("2009-02-10") decimal_date(date) # 2009.11
date <- ymd("2009-02-10") decimal_date(date) # 2009.11
Date-time must be a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
dst(x)
dst(x)
x |
a date-time object |
A date-time's daylight savings flag can not be set because it depends on the date-time's year, month, day, and hour values.
A logical. TRUE if DST is in force, FALSE if not, NA if unknown.
x <- ymd("2012-03-26") dst(x)
x <- ymd("2012-03-26") dst(x)
duration()
creates a duration object with the specified values. Entries
for different units are cumulative. durations display as the number of
seconds in a time span. When this number is large, durations also display an
estimate in larger units, however, the underlying object is always recorded
as a fixed number of seconds. For display and creation purposes, units are
converted to seconds using their most common lengths in seconds. Minutes = 60
seconds, hours = 3600 seconds, days = 86400 seconds, weeks = 604800. Units
larger than weeks are not used due to their variability.
duration(num = NULL, units = "seconds", ...) dseconds(x = 1) dminutes(x = 1) dhours(x = 1) ddays(x = 1) dweeks(x = 1) dmonths(x = 1) dyears(x = 1) dmilliseconds(x = 1) dmicroseconds(x = 1) dnanoseconds(x = 1) dpicoseconds(x = 1) is.duration(x)
duration(num = NULL, units = "seconds", ...) dseconds(x = 1) dminutes(x = 1) dhours(x = 1) ddays(x = 1) dweeks(x = 1) dmonths(x = 1) dyears(x = 1) dmilliseconds(x = 1) dmicroseconds(x = 1) dnanoseconds(x = 1) dpicoseconds(x = 1) is.duration(x)
num |
the number or a character vector of time units. In string representation all unambiguous name units and abbreviations and ISO 8601 formats are supported; 'm' stands for month and 'M' for minutes unless ISO 8601 "P" modifier is present (see examples). Fractional units are supported. |
units |
a character string that specifies the type of units that |
... |
a list of time units to be included in the duration and their amounts. Seconds, minutes, hours, days, weeks, months and years are supported. Durations of months and years assume that year consists of 365.25 days. |
x |
numeric value of the number of units to be contained in the duration. |
Durations record the exact number of seconds in a time span. They measure the exact passage of time but do not always align with measurements made in larger units of time such as hours, months and years. This is because the length of larger time units can be affected by conventions such as leap years and Daylight Savings Time. Base R provides a second class for measuring durations, the difftime class.
Duration objects can be easily created with the helper functions dweeks()
,
ddays()
, dminutes()
, dseconds()
. These objects can be added to and
subtracted to date- times to create a user interface similar to object
oriented programming.
a duration object
### Separate period and units vectors duration(90, "seconds") duration(1.5, "minutes") duration(-1, "days") ### Units as arguments duration(day = -1) duration(second = 90) duration(minute = 1.5) duration(mins = 1.5) duration(second = 3, minute = 1.5, hour = 2, day = 6, week = 1) duration(hour = 1, minute = -60) ### Parsing duration("2M 1sec") duration("2hours 2minutes 1second") duration("2d 2H 2M 2S") duration("2days 2hours 2mins 2secs") # Missing numerals default to 1. Repeated units are added up. duration("day day") ### ISO 8601 parsing duration("P3Y6M4DT12H30M5S") duration("P23DT23H") # M stands for months duration("10DT10M") # M stands for minutes duration("P23DT60H 20min 100 sec") # mixing ISO and lubridate style parsing # Comparison with characters (from v1.6.0) duration("day 2 sec") > "day 1sec" ## ELEMENTARY CONSTRUCTORS: dseconds(1) dminutes(3.5) x <- ymd("2009-08-03", tz = "America/Chicago") x + ddays(1) + dhours(6) + dminutes(30) x + ddays(100) - dhours(8) class(as.Date("2009-08-09") + ddays(1)) # retains Date class as.Date("2009-08-09") + dhours(12) class(as.Date("2009-08-09") + dhours(12)) # converts to POSIXt class to accomodate time units dweeks(1) - ddays(7) c(1:3) * dhours(1) # compare DST handling to durations boundary <- ymd_hms("2009-03-08 01:59:59", tz = "America/Chicago") boundary + days(1) # period boundary + ddays(1) # duration is.duration(as.Date("2009-08-03")) # FALSE is.duration(duration(days = 12.4)) # TRUE
### Separate period and units vectors duration(90, "seconds") duration(1.5, "minutes") duration(-1, "days") ### Units as arguments duration(day = -1) duration(second = 90) duration(minute = 1.5) duration(mins = 1.5) duration(second = 3, minute = 1.5, hour = 2, day = 6, week = 1) duration(hour = 1, minute = -60) ### Parsing duration("2M 1sec") duration("2hours 2minutes 1second") duration("2d 2H 2M 2S") duration("2days 2hours 2mins 2secs") # Missing numerals default to 1. Repeated units are added up. duration("day day") ### ISO 8601 parsing duration("P3Y6M4DT12H30M5S") duration("P23DT23H") # M stands for months duration("10DT10M") # M stands for minutes duration("P23DT60H 20min 100 sec") # mixing ISO and lubridate style parsing # Comparison with characters (from v1.6.0) duration("day 2 sec") > "day 1sec" ## ELEMENTARY CONSTRUCTORS: dseconds(1) dminutes(3.5) x <- ymd("2009-08-03", tz = "America/Chicago") x + ddays(1) + dhours(6) + dminutes(30) x + ddays(100) - dhours(8) class(as.Date("2009-08-09") + ddays(1)) # retains Date class as.Date("2009-08-09") + dhours(12) class(as.Date("2009-08-09") + dhours(12)) # converts to POSIXt class to accomodate time units dweeks(1) - ddays(7) c(1:3) * dhours(1) # compare DST handling to durations boundary <- ymd_hms("2009-03-08 01:59:59", tz = "America/Chicago") boundary + days(1) # period boundary + ddays(1) # duration is.duration(as.Date("2009-08-03")) # FALSE is.duration(duration(days = 12.4)) # TRUE
Duration is an S4 class that extends the Timespan class. Durations record the exact number of seconds in a time span. They measure the exact passage of time but do not always align with measurements made in larger units of time such as hours, months and years. This is because the exact length of larger time units can be affected by conventions such as leap years and Daylight Savings Time.
Durations provide a method for measuring generalized timespans when we wish to treat time as a mathematical quantity that increases in a uniform, monotone manner along a continuous numberline. They allow exact comparisons with other durations. See Period for an alternative way to measure timespans that better preserves clock times.
Durations class objects have one slot: .Data, a numeric object equal to the number of seconds in the duration.
The POSIXlt format allows you to create instants that do not exist in real life due to daylight savings time and other conventions. fit_to_timeline matches POSIXlt date-times to a real times. If an instant does not exist, fit to timeline will replace it with an NA. If an instant does exist, but has been paired with an incorrect timezone/daylight savings time combination, fit_to_timeline returns the instant with the correct combination.
fit_to_timeline(lt, class = "POSIXct", simple = FALSE)
fit_to_timeline(lt, class = "POSIXct", simple = FALSE)
lt |
a POSIXlt date-time object. |
class |
a character string that describes what type of object to return, POSIXlt or POSIXct. Defaults to POSIXct. This is an optimization to avoid needless conversions. |
simple |
if TRUE, lubridate makes no attempt to detect meaningless time-dates or to correct time zones. No NAs are produced and the most meaningful valid dates are returned instead. See examples. |
a POSIXct or POSIXlt object that contains no illusory date-times
## Not run: tricky <- structure(list( sec = c(5, 0, 0, -1), min = c(0L, 5L, 5L, 0L), hour = c(2L, 0L, 2L, 2L), mday = c(4L, 4L, 14L, 4L), mon = c(10L, 10L, 2L, 10L), year = c(112L, 112L, 110L, 112L), wday = c(0L, 0L, 0L, 0L), yday = c(308L, 308L, 72L, 308L), isdst = c(1L, 0L, 0L, 1L) ), .Names = c( "sec", "min", "hour", "mday", "mon", "year", "wday", "yday", "isdst" ), class = c("POSIXlt", "POSIXt"), tzone = c("America/Chicago", "CST", "CDT") ) tricky ## [1] "2012-11-04 02:00:00 CDT" Doesn't exist because clocks "fall back" to 1:00 CST ## [2] "2012-11-04 00:05:00 CST" Times are still CDT, not CST at this instant ## [3] "2010-03-14 02:00:00 CDT" DST gap ## [4] "2012-11-04 01:59:59 CDT" Does exist, but has deceptive internal structure fit_to_timeline(tricky) ## Returns: ## [1] "2012-11-04 02:00:00 CST" instant paired with correct tz & DST combination ## [2] "2012-11-04 00:05:00 CDT" instant paired with correct tz & DST combination ## [3] NA - fake time changed to NA (compare to as.POSIXct(tricky)) ## [4] "2012-11-04 01:59:59 CDT" -real instant, left as is fit_to_timeline(tricky, simple = TRUE) ## Returns valid time-dates by extrapolating CDT and CST zones: ## [1] "2012-11-04 01:00:05 CST" "2012-11-04 01:05:00 CDT" ## [3] "2010-03-14 03:05:00 CDT" "2012-11-04 01:59:59 CDT" ## End(Not run)
## Not run: tricky <- structure(list( sec = c(5, 0, 0, -1), min = c(0L, 5L, 5L, 0L), hour = c(2L, 0L, 2L, 2L), mday = c(4L, 4L, 14L, 4L), mon = c(10L, 10L, 2L, 10L), year = c(112L, 112L, 110L, 112L), wday = c(0L, 0L, 0L, 0L), yday = c(308L, 308L, 72L, 308L), isdst = c(1L, 0L, 0L, 1L) ), .Names = c( "sec", "min", "hour", "mday", "mon", "year", "wday", "yday", "isdst" ), class = c("POSIXlt", "POSIXt"), tzone = c("America/Chicago", "CST", "CDT") ) tricky ## [1] "2012-11-04 02:00:00 CDT" Doesn't exist because clocks "fall back" to 1:00 CST ## [2] "2012-11-04 00:05:00 CST" Times are still CDT, not CST at this instant ## [3] "2010-03-14 02:00:00 CDT" DST gap ## [4] "2012-11-04 01:59:59 CDT" Does exist, but has deceptive internal structure fit_to_timeline(tricky) ## Returns: ## [1] "2012-11-04 02:00:00 CST" instant paired with correct tz & DST combination ## [2] "2012-11-04 00:05:00 CDT" instant paired with correct tz & DST combination ## [3] NA - fake time changed to NA (compare to as.POSIXct(tricky)) ## [4] "2012-11-04 01:59:59 CDT" -real instant, left as is fit_to_timeline(tricky, simple = TRUE) ## Returns valid time-dates by extrapolating CDT and CST zones: ## [1] "2012-11-04 01:00:05 CST" "2012-11-04 01:05:00 CDT" ## [3] "2010-03-14 03:05:00 CDT" "2012-11-04 01:59:59 CDT" ## End(Not run)
force_tz
returns the date-time that has the same clock time as input time,
but in the new time zone. force_tzs
is the parallel version of force_tz
,
meaning that every element from time
argument is matched with the
corresponding time zone in tzones
argument.
force_tz(time, tzone = "", ...) ## Default S3 method: force_tz(time, tzone = "", roll_dst = c("NA", "post"), roll = NULL, ...) force_tzs( time, tzones, tzone_out = "UTC", roll_dst = c("NA", "post"), roll = NULL )
force_tz(time, tzone = "", ...) ## Default S3 method: force_tz(time, tzone = "", roll_dst = c("NA", "post"), roll = NULL, ...) force_tzs( time, tzones, tzone_out = "UTC", roll_dst = c("NA", "post"), roll = NULL )
time |
a POSIXct, POSIXlt, Date, chron date-time object, or a data.frame
object. When a data.frame all POSIXt elements of a data.frame are processed
with |
tzone |
a character string containing the time zone to convert to. R must recognize the name contained in the string as a time zone on your system. |
... |
Parameters passed to other methods. |
roll_dst |
is a string vector of length one or two. When two values are supplied they specify how to roll date-times when they fall into "skipped" and "repeated" DST transitions respectively. A single value is replicated to the length of two. Possible values are: * `pre` - Use the time before the transition boundary. * `boundary` - Use the time exactly at the boundary transition. * `post` - Use the time after the boundary transition. * `xfirst` - crossed-first: First time which occurred when crossing the boundary. For addition with positive units pre interval is crossed first and post interval last. With negative units post interval is crossed first, pre - last. For subtraction the logic is reversed. * `xlast` - crossed-last. * `NA` - Produce NAs when the resulting time falls inside the problematic interval. For example 'roll_dst = c("NA", "pre") indicates that for skiped intervals return NA and for repeated times return the earlier time. When multiple units are supplied the meaning of "negative period" is determined by
the largest unit. For example "xfirst" and "xlast" make sense for addition and subtraction only. An error is raised if an attempt is made to use them with other functions. |
roll |
deprecated, same as |
tzones |
character vector of timezones to be "enforced" on |
tzone_out |
timezone of the returned date-time vector (for |
Although the new date-time has the same clock time (e.g. the same values in the year, month, days, etc. elements) it is a different moment of time than the input date-time.
As R date-time vectors cannot hold elements with non-uniform time zones,
force_tzs
returns a vector with time zone tzone_out
, UTC by default.
a POSIXct object in the updated time zone
x <- ymd_hms("2009-08-07 00:00:01", tz = "America/New_York") force_tz(x, "UTC") force_tz(x, "Europe/Amsterdam") ## DST skip: y <- ymd_hms("2010-03-14 02:05:05 UTC") force_tz(y, "America/New_York", roll_dst = "NA") force_tz(y, "America/New_York", roll_dst = "pre") force_tz(y, "America/New_York", roll_dst = "boundary") force_tz(y, "America/New_York", roll_dst = "post") ## DST repeat y <- ymd_hms("2014-11-02 01:35:00", tz = "UTC") force_tz(y, "America/New_York", roll_dst = "NA") force_tz(y, "America/New_York", roll_dst = "pre") force_tz(y, "America/New_York", roll_dst = "boundary") force_tz(y, "America/New_York", roll_dst = "post") ## DST skipped and repeated y <- ymd_hms("2010-03-14 02:05:05 UTC", "2014-11-02 01:35:00", tz = "UTC") force_tz(y, "America/New_York", roll_dst = c("NA", "pre")) force_tz(y, "America/New_York", roll_dst = c("boundary", "post")) ## Heterogeneous time-zones: x <- ymd_hms(c("2009-08-07 00:00:01", "2009-08-07 01:02:03")) force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam")) force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam"), tzone_out = "America/New_York") x <- ymd_hms("2009-08-07 00:00:01") force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam"))
x <- ymd_hms("2009-08-07 00:00:01", tz = "America/New_York") force_tz(x, "UTC") force_tz(x, "Europe/Amsterdam") ## DST skip: y <- ymd_hms("2010-03-14 02:05:05 UTC") force_tz(y, "America/New_York", roll_dst = "NA") force_tz(y, "America/New_York", roll_dst = "pre") force_tz(y, "America/New_York", roll_dst = "boundary") force_tz(y, "America/New_York", roll_dst = "post") ## DST repeat y <- ymd_hms("2014-11-02 01:35:00", tz = "UTC") force_tz(y, "America/New_York", roll_dst = "NA") force_tz(y, "America/New_York", roll_dst = "pre") force_tz(y, "America/New_York", roll_dst = "boundary") force_tz(y, "America/New_York", roll_dst = "post") ## DST skipped and repeated y <- ymd_hms("2010-03-14 02:05:05 UTC", "2014-11-02 01:35:00", tz = "UTC") force_tz(y, "America/New_York", roll_dst = c("NA", "pre")) force_tz(y, "America/New_York", roll_dst = c("boundary", "post")) ## Heterogeneous time-zones: x <- ymd_hms(c("2009-08-07 00:00:01", "2009-08-07 01:02:03")) force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam")) force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam"), tzone_out = "America/New_York") x <- ymd_hms("2009-08-07 00:00:01") force_tzs(x, tzones = c("America/New_York", "Europe/Amsterdam"))
Format in ISO8601 character format
format_ISO8601(x, usetz = FALSE, precision = NULL, ...)
format_ISO8601(x, usetz = FALSE, precision = NULL, ...)
x |
An object to convert to ISO8601 character format. |
usetz |
Include the time zone in the formatting. If
|
precision |
The amount of precision to represent with
substrings of "ymdhms", as "y"ear, "m"onth, "d"ay, "h"our,
"m"inute, and "s"econd. (e.g. "ymdhm" would show precision
through minutes. When |
... |
Additional arguments to methods. |
A character vector of ISO8601-formatted text.
https://en.wikipedia.org/wiki/ISO_8601
format_ISO8601(as.Date("02-01-2018", format = "%m-%d-%Y")) format_ISO8601(as.POSIXct("2018-02-01 03:04:05", tz = "EST"), usetz = TRUE) format_ISO8601(as.POSIXct("2018-02-01 03:04:05", tz = "EST"), precision = "ymdhm")
format_ISO8601(as.Date("02-01-2018", format = "%m-%d-%Y")) format_ISO8601(as.POSIXct("2018-02-01 03:04:05", tz = "EST"), usetz = TRUE) format_ISO8601(as.POSIXct("2018-02-01 03:04:05", tz = "EST"), precision = "ymdhm")
Guess possible date-times formats from a character vector.
guess_formats( x, orders, locale = Sys.getlocale("LC_TIME"), preproc_wday = TRUE, print_matches = FALSE )
guess_formats( x, orders, locale = Sys.getlocale("LC_TIME"), preproc_wday = TRUE, print_matches = FALSE )
x |
input vector of date-times. |
orders |
format orders to look for. See examples. |
locale |
locale to use. Defaults to the current locale. |
preproc_wday |
whether to preprocess weekday names. Internal
optimization used by |
print_matches |
for development purposes mainly. If |
a vector of matched formats
x <- c('February 20th 1973', "february 14, 2004", "Sunday, May 1, 2000", "Sunday, May 1, 2000", "february 14, 04", 'Feb 20th 73', "January 5 1999 at 7pm", "jan 3 2010", "Jan 1, 1999", "jan 3 10", "01 3 2010", "1 3 10", '1 13 89', "5/27/1979", "12/31/99", "DOB:12/11/00", "-----------", 'Thu, 1 July 2004 22:30:00', 'Thu, 1st of July 2004 at 22:30:00', 'Thu, 1July 2004 at 22:30:00', 'Thu, 1July2004 22:30:00', 'Thu, 1July04 22:30:00', "21 Aug 2011, 11:15:34 pm", "-----------", "1979-05-27 05:00:59", "1979-05-27", "-----------", "3 jan 2000", "17 april 85", "27/5/1979", '20 01 89', '00/13/10', "-------", "14 12 00", "03:23:22 pm") guess_formats(x, "BdY") guess_formats(x, "Bdy") ## m also matches b and B; y also matches Y guess_formats(x, "mdy", print_matches = TRUE) ## T also matches IMSp order guess_formats(x, "T", print_matches = TRUE) ## b and B are equivalent and match, both, abreviated and full names guess_formats(x, c("mdY", "BdY", "Bdy", "bdY", "bdy"), print_matches = TRUE) guess_formats(x, c("dmy", "dbY", "dBy", "dBY"), print_matches = TRUE) guess_formats(x, c("dBY HMS", "dbY HMS", "dmyHMS", "BdY H"), print_matches = TRUE) guess_formats(x, c("ymd HMS"), print_matches = TRUE)
x <- c('February 20th 1973', "february 14, 2004", "Sunday, May 1, 2000", "Sunday, May 1, 2000", "february 14, 04", 'Feb 20th 73', "January 5 1999 at 7pm", "jan 3 2010", "Jan 1, 1999", "jan 3 10", "01 3 2010", "1 3 10", '1 13 89', "5/27/1979", "12/31/99", "DOB:12/11/00", "-----------", 'Thu, 1 July 2004 22:30:00', 'Thu, 1st of July 2004 at 22:30:00', 'Thu, 1July 2004 at 22:30:00', 'Thu, 1July2004 22:30:00', 'Thu, 1July04 22:30:00', "21 Aug 2011, 11:15:34 pm", "-----------", "1979-05-27 05:00:59", "1979-05-27", "-----------", "3 jan 2000", "17 april 85", "27/5/1979", '20 01 89', '00/13/10', "-------", "14 12 00", "03:23:22 pm") guess_formats(x, "BdY") guess_formats(x, "Bdy") ## m also matches b and B; y also matches Y guess_formats(x, "mdy", print_matches = TRUE) ## T also matches IMSp order guess_formats(x, "T", print_matches = TRUE) ## b and B are equivalent and match, both, abreviated and full names guess_formats(x, c("mdY", "BdY", "Bdy", "bdY", "bdy"), print_matches = TRUE) guess_formats(x, c("dmy", "dbY", "dBy", "dBY"), print_matches = TRUE) guess_formats(x, c("dBY HMS", "dbY HMS", "dmyHMS", "BdY H"), print_matches = TRUE) guess_formats(x, c("ymd HMS"), print_matches = TRUE)
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
hour(x) hour(x) <- value
hour(x) hour(x) <- value
x |
a date-time object |
value |
numeric value to be assigned to the |
the hours element of x as a decimal number
x <- ymd("2012-03-26") hour(x) hour(x) <- 1 hour(x) <- 25 hour(x) > 2
x <- ymd("2012-03-26") hour(x) hour(x) <- 1 hour(x) <- 25 hour(x) > 2
Interval
objectsinterval()
creates an Interval object with the specified start and
end dates. If the start date occurs before the end date, the interval will be
positive. Otherwise, it will be negative. Character vectors in ISO 8601
format are supported from v1.7.2.
int_start()
/int_end()
and int_start<-()
/int_end<-()
are
"accessors" and "setters" respectively of the start/end date of an
interval.
int_flip()
reverses the order of the start date and end date in an
interval. The new interval takes place during the same timespan as the
original interval, but has the opposite direction.
int_shift()
shifts the start and end dates of an interval up or down the
timeline by a specified amount. Note that this may change the exact length of
the interval if the interval is shifted by a Period object. Intervals shifted
by a Duration or difftime object will retain their exact length in seconds.
int_overlaps()
tests if two intervals overlap.
int_standardize()
ensures all intervals in an interval object are
positive. If an interval is not positive, flip it so that it retains its
endpoints but becomes positive.
int_aligns()
tests if two intervals share an endpoint. The direction of
each interval is ignored. int_align tests whether the earliest or latest
moments of each interval occur at the same time.
int_diff()
returns the intervals that occur between the elements of a
vector of date-times. int_diff()
is similar to the POSIXt and Date
methods of diff()
, but returns an Interval object instead
of a difftime object.
interval(start = NULL, end = NULL, tzone = tz(start)) start %--% end is.interval(x) int_start(int) int_start(int) <- value int_end(int) int_end(int) <- value int_length(int) int_flip(int) int_shift(int, by) int_overlaps(int1, int2) int_standardize(int) int_aligns(int1, int2) int_diff(times)
interval(start = NULL, end = NULL, tzone = tz(start)) start %--% end is.interval(x) int_start(int) int_start(int) <- value int_end(int) int_end(int) <- value int_length(int) int_flip(int) int_shift(int, by) int_overlaps(int1, int2) int_standardize(int) int_aligns(int1, int2) int_diff(times)
start , end
|
POSIXt, Date or a character vectors. When |
tzone |
a recognized timezone to display the interval in |
x |
an R object |
int |
an interval object |
value |
interval's start/end to be assigned to |
by |
A period or duration object to shift by (for |
int1 |
an Interval object (for |
int2 |
an Interval object (for |
times |
A vector of POSIXct, POSIXlt or Date class date-times (for
|
Intervals are time spans bound by two real date-times. Intervals can be
accurately converted to either period or duration objects using
as.period()
, as.duration()
. Since an interval is anchored to a fixed
history of time, both the exact number of seconds that passed and the number
of variable length time units that occurred during the interval can be
calculated.
interval()
– Interval object.
int_start()
and int_end()
return a POSIXct date object when
used as an accessor. Nothing when used as a setter.
int_length()
– numeric length of the interval in
seconds. A negative number connotes a negative interval.
int_flip()
– flipped interval object
int_shift()
– an Interval object
int_overlaps()
– logical, TRUE if int1 and int2 overlap by at
least one second. FALSE otherwise
int_aligns()
– logical, TRUE if int1 and int2 begin or end on the
same moment. FALSE otherwise
int_diff()
– interval object that contains the n-1 intervals
between the n date-time in times
Interval, as.interval()
, %within%
interval(ymd(20090201), ymd(20090101)) date1 <- ymd_hms("2009-03-08 01:59:59") date2 <- ymd_hms("2000-02-29 12:00:00") interval(date2, date1) interval(date1, date2) span <- interval(ymd(20090101), ymd(20090201)) ### ISO Intervals interval("2007-03-01T13:00:00Z/2008-05-11T15:30:00Z") interval("2007-03-01T13:00:00Z/P1Y2M10DT2H30M") interval("P1Y2M10DT2H30M/2008-05-11T15:30:00Z") interval("2008-05-11/P2H30M") ### More permisive parsing (as long as there are no intermittent / characters) interval("2008 05 11/P2hours 30minutes") interval("08 05 11/P 2h 30m") is.interval(period(months = 1, days = 15)) # FALSE is.interval(interval(ymd(20090801), ymd(20090809))) # TRUE int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_start(int) int_start(int) <- ymd("2001-06-01") int int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_end(int) int_end(int) <- ymd("2002-06-01") int int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_length(int) int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_flip(int) int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_shift(int, duration(days = 11)) int_shift(int, duration(hours = -1)) int1 <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-06-01")) int3 <- interval(ymd("2003-01-01"), ymd("2004-01-01")) int_overlaps(int1, int2) # TRUE int_overlaps(int1, int3) # FALSE int <- interval(ymd("2002-01-01"), ymd("2001-01-01")) int_standardize(int) int1 <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-01-01")) int3 <- interval(ymd("2003-01-01"), ymd("2004-01-01")) int_aligns(int1, int2) # TRUE int_aligns(int1, int3) # FALSE dates <- now() + days(1:10) int_diff(dates)
interval(ymd(20090201), ymd(20090101)) date1 <- ymd_hms("2009-03-08 01:59:59") date2 <- ymd_hms("2000-02-29 12:00:00") interval(date2, date1) interval(date1, date2) span <- interval(ymd(20090101), ymd(20090201)) ### ISO Intervals interval("2007-03-01T13:00:00Z/2008-05-11T15:30:00Z") interval("2007-03-01T13:00:00Z/P1Y2M10DT2H30M") interval("P1Y2M10DT2H30M/2008-05-11T15:30:00Z") interval("2008-05-11/P2H30M") ### More permisive parsing (as long as there are no intermittent / characters) interval("2008 05 11/P2hours 30minutes") interval("08 05 11/P 2h 30m") is.interval(period(months = 1, days = 15)) # FALSE is.interval(interval(ymd(20090801), ymd(20090809))) # TRUE int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_start(int) int_start(int) <- ymd("2001-06-01") int int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_end(int) int_end(int) <- ymd("2002-06-01") int int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_length(int) int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_flip(int) int <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int_shift(int, duration(days = 11)) int_shift(int, duration(hours = -1)) int1 <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-06-01")) int3 <- interval(ymd("2003-01-01"), ymd("2004-01-01")) int_overlaps(int1, int2) # TRUE int_overlaps(int1, int3) # FALSE int <- interval(ymd("2002-01-01"), ymd("2001-01-01")) int_standardize(int) int1 <- interval(ymd("2001-01-01"), ymd("2002-01-01")) int2 <- interval(ymd("2001-06-01"), ymd("2002-01-01")) int3 <- interval(ymd("2003-01-01"), ymd("2004-01-01")) int_aligns(int1, int2) # TRUE int_aligns(int1, int3) # FALSE dates <- now() + days(1:10) int_diff(dates)
Interval is an S4 class that extends the Timespan class. An Interval object records one or more spans of time. Intervals record these timespans as a sequence of seconds that begin at a specified date. Since intervals are anchored to a precise moment of time, they can accurately be converted to Period or Duration class objects. This is because we can observe the length in seconds of each period that begins on a specific date. Contrast this to a generalized period, which may not have a consistent length in seconds (e.g. the number of seconds in a year will change if it is a leap year).
Intervals can be both negative and positive. Negative intervals progress backwards from the start date; positive intervals progress forwards.
Interval class objects have two slots: .Data, a numeric object equal to the number of seconds in the interval; and start, a POSIXct object that specifies the time when the interval starts.
Date()
mirrors primitive contructors in base R (double()
, character()
etc.)
is.Date(x) Date(length = 0L) NA_Date_
is.Date(x) Date(length = 0L) NA_Date_
x |
an R object |
length |
A non-negative number specifying the desired length. Supplying an argument of length other than one is an error. |
An object of class Date
of length 1.
is.instant()
, is.timespan()
, is.POSIXt()
, POSIXct()
is.Date(as.Date("2009-08-03")) # TRUE is.Date(difftime(now() + 5, now())) # FALSE
is.Date(as.Date("2009-08-03")) # TRUE is.Date(difftime(now() + 5, now())) # FALSE
Is x a difftime object?
is.difftime(x)
is.difftime(x)
x |
an R object |
TRUE if x is a difftime object, FALSE otherwise.
is.instant()
, is.timespan()
, is.interval()
,
is.period()
.
is.difftime(as.Date("2009-08-03")) # FALSE is.difftime(make_difftime(days = 12.4)) # TRUE
is.difftime(as.Date("2009-08-03")) # FALSE is.difftime(make_difftime(days = 12.4)) # TRUE
An instant is a specific moment in time. Most common date-time objects (e.g, POSIXct, POSIXlt, and Date objects) are instants.
is.instant(x) is.timepoint(x)
is.instant(x) is.timepoint(x)
x |
an R object |
TRUE if x is a POSIXct, POSIXlt, or Date object, FALSE otherwise.
is.timespan()
, is.POSIXt()
, is.Date()
is.instant(as.Date("2009-08-03")) # TRUE is.timepoint(5) # FALSE
is.instant(as.Date("2009-08-03")) # TRUE is.timepoint(5) # FALSE
POSIXct()
mirrors primitive contructors in base R (double()
,
character()
etc.)
is.POSIXt(x) is.POSIXlt(x) is.POSIXct(x) POSIXct(length = 0L, tz = "UTC") NA_POSIXct_
is.POSIXt(x) is.POSIXlt(x) is.POSIXct(x) POSIXct(length = 0L, tz = "UTC") NA_POSIXct_
x |
an R object |
length |
A non-negative number specifying the desired length. Supplying an argument of length other than one is an error. |
tz |
a timezone (defaults to "utc") |
An object of class POSIXct
(inherits from POSIXt
) of length 1.
TRUE if x is a POSIXct or POSIXlt object, FALSE otherwise.
is.instant()
, is.timespan()
, is.Date()
is.POSIXt(as.Date("2009-08-03")) is.POSIXt(as.POSIXct("2009-08-03"))
is.POSIXt(as.Date("2009-08-03")) is.POSIXt(as.POSIXct("2009-08-03"))
Is x a length of time?
is.timespan(x)
is.timespan(x)
x |
an R object |
TRUE if x is a period, interval, duration, or difftime object, FALSE otherwise.
is.instant()
, is.duration()
, is.difftime()
, is.period()
, is.interval()
is.timespan(as.Date("2009-08-03")) # FALSE is.timespan(duration(second = 1)) # TRUE
is.timespan(as.Date("2009-08-03")) # FALSE is.timespan(duration(second = 1)) # TRUE
This data set contains play by play statistics of each Los Angeles Lakers basketball game in the 2008-2009 season. Data includes the date, opponent, and type of each game (home or away). Each play is described by the time on the game clock when the play was made, the period in which the play was attempted, the type of play, the player and team who made the play, the result of the play, and the location on the court where each play was made.
Originally taken from www.basketballgeek.com/data/.
If x is a recognized date-time object, leap_year will return whether x occurs during a leap year. If x is a number, leap_year returns whether it would be a leap year under the Gregorian calendar.
leap_year(date)
leap_year(date)
date |
a date-time object or a year |
TRUE if x is a leap year, FALSE otherwise
x <- as.Date("2009-08-02") leap_year(x) # FALSE leap_year(2009) # FALSE leap_year(2008) # TRUE leap_year(1900) # FALSE leap_year(2000) # TRUE
x <- as.Date("2009-08-02") leap_year(x) # FALSE leap_year(2009) # FALSE leap_year(2008) # TRUE leap_year(1900) # FALSE leap_year(2000) # TRUE
local_time
retrieves day clock time in specified time zones. Computation is
vectorized over both dt
and tz
arguments, the shortest is recycled in
accordance with standard R rules.
local_time(dt, tz = NULL, units = "secs")
local_time(dt, tz = NULL, units = "secs")
dt |
a date-time object. |
tz |
a character vector of timezones for which to compute the local time. |
units |
passed directly to |
x <- ymd_hms(c("2009-08-07 01:02:03", "2009-08-07 10:20:30")) local_time(x, units = "secs") local_time(x, units = "hours") local_time(x, "Europe/Amsterdam") local_time(x, "Europe/Amsterdam") == local_time(with_tz(x, "Europe/Amsterdam")) x <- ymd_hms("2009-08-07 01:02:03") local_time(x, c("America/New_York", "Europe/Amsterdam", "Asia/Shanghai"), unit = "hours")
x <- ymd_hms(c("2009-08-07 01:02:03", "2009-08-07 10:20:30")) local_time(x, units = "secs") local_time(x, units = "hours") local_time(x, "Europe/Amsterdam") local_time(x, "Europe/Amsterdam") == local_time(with_tz(x, "Europe/Amsterdam")) x <- ymd_hms("2009-08-07 01:02:03") local_time(x, c("America/New_York", "Europe/Amsterdam", "Asia/Shanghai"), unit = "hours")
make_datetime()
is a very fast drop-in replacement for
base::ISOdate()
and base::ISOdatetime()
. make_date()
produces
objects of class Date
.
make_datetime( year = 1970L, month = 1L, day = 1L, hour = 0L, min = 0L, sec = 0, tz = "UTC" ) make_date(year = 1970L, month = 1L, day = 1L)
make_datetime( year = 1970L, month = 1L, day = 1L, hour = 0L, min = 0L, sec = 0, tz = "UTC" ) make_date(year = 1970L, month = 1L, day = 1L)
year |
numeric year |
month |
numeric month |
day |
numeric day |
hour |
numeric hour |
min |
numeric minute |
sec |
numeric second |
tz |
time zone. Defaults to UTC. |
Input vectors are silently recycled. All inputs except sec
are
silently converted to integer vectors; sec
can be either integer or
double.
make_datetime(year = 1999, month = 12, day = 22, sec = 10) make_datetime(year = 1999, month = 12, day = 22, sec = c(10, 11))
make_datetime(year = 1999, month = 12, day = 22, sec = 10) make_datetime(year = 1999, month = 12, day = 22, sec = c(10, 11))
make_difftime()
creates a difftime object with the specified number of
units. Entries for different units are cumulative. difftime displays
durations in various units, but these units are estimates given for
convenience. The underlying object is always recorded as a fixed number of
seconds.
make_difftime(num = NULL, units = "auto", ...)
make_difftime(num = NULL, units = "auto", ...)
num |
Optional number of seconds |
units |
a character vector that lists the type of units to use for the
display of the return value (see examples). If |
... |
a list of time units to be included in the difftime and their amounts. Seconds,
minutes, hours, days, and weeks are supported. Normally only one of |
Conceptually, difftime objects are a type of duration. They measure the exact passage of time but do not always align with measurements made in larger units of time such as hours, months and years. This is because the length of larger time units can be affected by conventions such as leap years and Daylight Savings Time. lubridate provides a second class for measuring durations, the Duration class.
a difftime object
make_difftime(1) make_difftime(60) make_difftime(3600) make_difftime(3600, units = "minute") # Time difference of 60 mins make_difftime(second = 90) # Time difference of 1.5 mins make_difftime(minute = 1.5) # Time difference of 1.5 mins make_difftime(second = 3, minute = 1.5, hour = 2, day = 6, week = 1) # Time difference of 13.08441 days make_difftime(hour = 1, minute = -60) # Time difference of 0 secs make_difftime(day = -1) # Time difference of -1 days make_difftime(120, day = -1, units = "minute") # Time differences in mins
make_difftime(1) make_difftime(60) make_difftime(3600) make_difftime(3600, units = "minute") # Time difference of 60 mins make_difftime(second = 90) # Time difference of 1.5 mins make_difftime(minute = 1.5) # Time difference of 1.5 mins make_difftime(second = 3, minute = 1.5, hour = 2, day = 6, week = 1) # Time difference of 13.08441 days make_difftime(hour = 1, minute = -60) # Time difference of 0 secs make_difftime(day = -1) # Time difference of -1 days make_difftime(120, day = -1, units = "minute") # Time differences in mins
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
minute(x) minute(x) <- value
minute(x) minute(x) <- value
x |
a date-time object |
value |
numeric value to be assigned |
the minutes element of x as a decimal number
x <- ymd("2012-03-26") minute(x) minute(x) <- 1 minute(x) <- 61 minute(x) > 2
x <- ymd("2012-03-26") minute(x) minute(x) <- 1 minute(x) <- 61 minute(x) > 2
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
month(x, label = FALSE, abbr = TRUE, locale = Sys.getlocale("LC_TIME")) month(x) <- value
month(x, label = FALSE, abbr = TRUE, locale = Sys.getlocale("LC_TIME")) month(x) <- value
x |
a date-time object |
label |
logical. TRUE will display the month as a character string such as "January." FALSE will display the month as a number. |
abbr |
logical. FALSE will display the month as a character string label, such as "January". TRUE will display an abbreviated version of the label, such as "Jan". abbr is disregarded if label = FALSE. |
locale |
for month, locale to use for month names. Default to current locale. |
value |
a numeric object |
If label = FALSE
: month as number (1-12, 1 = January, 12 = December),
otherwise as an ordered factor.
x <- ymd("2012-03-26") month(x) month(x) <- 1 month(x) <- 13 month(x) > 3 month(ymd(080101)) month(ymd(080101), label = TRUE) month(ymd(080101), label = TRUE, abbr = FALSE) month(ymd(080101) + months(0:11), label = TRUE)
x <- ymd("2012-03-26") month(x) month(x) <- 1 month(x) <- 13 month(x) > 3 month(ymd(080101)) month(ymd(080101), label = TRUE) month(ymd(080101), label = TRUE, abbr = FALSE) month(ymd(080101) + months(0:11), label = TRUE)
Transforms a character or numeric vector into a period object with the
specified number of hours, minutes, and seconds. hms()
recognizes all
non-numeric characters except '-' as separators ('-' is used for negative
durations
). After hours, minutes and seconds have been parsed, the
remaining input is ignored.
ms(..., quiet = FALSE, roll = FALSE) hm(..., quiet = FALSE, roll = FALSE) hms(..., quiet = FALSE, roll = FALSE)
ms(..., quiet = FALSE, roll = FALSE) hm(..., quiet = FALSE, roll = FALSE) hms(..., quiet = FALSE, roll = FALSE)
... |
a character vector of hour minute second triples |
quiet |
logical. If |
roll |
logical. If |
a vector of period objects
ms(c("09:10", "09:02", "1:10")) ms("7 6") ms("6,5") hm(c("09:10", "09:02", "1:10")) hm("7 6") hm("6,5") x <- c("09:10:01", "09:10:02", "09:10:03") hms(x) hms("7 6 5", "3:23:::2", "2 : 23 : 33", "Finished in 9 hours, 20 min and 4 seconds")
ms(c("09:10", "09:02", "1:10")) ms("7 6") ms("6,5") hm(c("09:10", "09:02", "1:10")) hm("7 6") hm("6,5") x <- c("09:10:01", "09:10:02", "09:10:03") hms(x) hms("7 6 5", "3:23:::2", "2 : 23 : 33", "Finished in 9 hours, 20 min and 4 seconds")
The current day and time
now(tzone = "") today(tzone = "")
now(tzone = "") today(tzone = "")
tzone |
a character vector specifying which time zone you would like the current time in. tzone defaults to your computer's system timezone. You can retrieve the current time in the Universal Coordinated Time (UTC) with now("UTC"). |
now
- the current datetime as a POSIXct
object
now() now("GMT") now("") now() == now() # would be TRUE if computer processed both at the same instant now() < now() # TRUE now() > now() # FALSE today() today("GMT") today() == today("GMT") # not always true today() < as.Date("2999-01-01") # TRUE (so far)
now() now("GMT") now("") now() == now() # would be TRUE if computer processed both at the same instant now() < now() # TRUE now() > now() # FALSE today() today("GMT") today() == today("GMT") # not always true today() < as.Date("2999-01-01") # TRUE (so far)
Origin is the date-time for 1970-01-01 UTC in POSIXct format. This date-time is the origin for the numbering system used by POSIXct, POSIXlt, chron, and Date classes.
origin
origin
An object of class POSIXct
(inherits from POSIXt
) of length 1.
origin
origin
parse_date_time()
parses an input vector into POSIXct date-time
object. It differs from base::strptime()
in two respects. First,
it allows specification of the order in which the formats occur without the
need to include separators and the %
prefix. Such a formatting argument is
referred to as "order". Second, it allows the user to specify several
format-orders to handle heterogeneous date-time character
representations.
parse_date_time2()
is a fast C parser of numeric orders.
fast_strptime()
is a fast C parser of numeric formats only
that accepts explicit format arguments, just like base::strptime()
.
parse_date_time( x, orders, tz = "UTC", truncated = 0, quiet = FALSE, locale = Sys.getlocale("LC_TIME"), select_formats = .select_formats, exact = FALSE, train = TRUE, drop = FALSE ) parse_date_time2( x, orders, tz = "UTC", exact = FALSE, lt = FALSE, cutoff_2000 = 68L ) fast_strptime(x, format, tz = "UTC", lt = TRUE, cutoff_2000 = 68L)
parse_date_time( x, orders, tz = "UTC", truncated = 0, quiet = FALSE, locale = Sys.getlocale("LC_TIME"), select_formats = .select_formats, exact = FALSE, train = TRUE, drop = FALSE ) parse_date_time2( x, orders, tz = "UTC", exact = FALSE, lt = FALSE, cutoff_2000 = 68L ) fast_strptime(x, format, tz = "UTC", lt = TRUE, cutoff_2000 = 68L)
x |
a character or numeric vector of dates |
orders |
a character vector of date-time formats. Each order string is
a series of formatting characters as listed in |
tz |
a character string that specifies the time zone with which to parse the dates |
truncated |
integer, number of formats that can be missing. The most
common type of irregularity in date-time data is the truncation due to
rounding or unavailability of the time stamp. If the |
quiet |
logical. If |
locale |
locale to be used, see locales. On Linux systems you
can use |
select_formats |
A function to select actual formats for parsing from a
set of formats which matched a training subset of |
exact |
logical. If |
train |
logical, default |
drop |
logical, default |
lt |
logical. If |
cutoff_2000 |
integer. For |
format |
a vector of formats. If multiple formats supplied they are
applied in turn till success. The formats should include all the
separators and each format letter must be prefixed with %, just as in the
format argument of |
When several format-orders are specified, parse_date_time()
selects
(guesses) format-orders based on a training subset of the input
strings. After guessing the formats are ordered according to the performance
on the training set and applied recursively on the entire input vector. You
can disable training with train = FALSE
.
parse_date_time()
, and all derived functions, such as ymd_hms()
,
ymd()
, etc., will drop into fast_strptime()
instead of
base::strptime()
whenever the guessed from the input data formats are all
numeric.
The list below contains formats recognized by lubridate. For numeric
formats leading 0s are optional. As compared to base::strptime()
, some of
the formats are new or have been extended for efficiency reasons. These
formats are marked with "(*)" below. Fast parsers parse_date_time2()
and
fast_strptime()
accept only formats marked with "(!)".
a
Abbreviated weekday name in the current locale. (Also matches full name)
A
Full weekday name in the current locale. (Also matches abbreviated name).
You don't need to specify a
and A
formats explicitly. Wday is
automatically handled if preproc_wday = TRUE
b
(!)Abbreviated or full month name in the current locale. The C parser currently understands only English month names.
B
(!)Same as b.
d
(!)Day of the month as decimal number (01–31 or 0–31)
H
(!)Hours as decimal number (00–24 or 0–24).
I
(!)Hours as decimal number (01–12 or 1–12).
j
Day of year as decimal number (001–366 or 1–366).
q
(!*)Quarter (1–4). The quarter month is added to the parsed
month if m
element is present.
m
(!*)Month as decimal number (01–12 or 1–12). For
parse_date_time
also matches abbreviated and full months names as b
and B
formats. C parser understands only English month names.
M
(!)Minute as decimal number (00–59 or 0–59).
p
(!)AM/PM indicator in the locale. Commonly used in conjunction
with I
and not with H
. But lubridate's C parser accepts H
format as long as hour is not greater than 12. C parser understands only
English locale AM/PM indicator.
S
(!)Second as decimal number (00–61 or 0–61), allowing for up to two leap-seconds (but POSIX-compliant implementations will ignore leap seconds).
OS
Fractional second.
U
Week of the year as decimal number (00–53 or 0–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.
w
Weekday as decimal number (0–6, Sunday is 0).
W
Week of the year as decimal number (00–53 or 0–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1). The UK convention.
y
(!*)Year without century (00–99 or 0–99). In
parse_date_time()
also matches year with century (Y format).
Y
(!)Year with century.
z
(!*)ISO8601 signed offset in hours and minutes from UTC. For
example -0800
, -08:00
or -08
, all represent 8 hours behind UTC. This
format also matches the Z (Zulu) UTC indicator. Because base::strptime()
doesn't fully support ISO8601 this format is implemented as an union of 4
formats: Ou (Z), Oz (-0800), OO (-08:00) and Oo (-08). You can use these
formats as any other but it is rarely necessary. parse_date_time2()
and
fast_strptime()
support all of these formats.
Om
(!*)Matches numeric month and English alphabetic months (Both, long and abbreviated forms).
Op
(!*)Matches AM/PM English indicator.
r
(*)Matches Ip
and H
orders.
R
(*)Matches HM
andIMp
orders.
T
(*)Matches IMSp
, HMS
, and HMOS
orders.
a vector of POSIXct date-time objects
parse_date_time()
(and the derivatives ymd()
, ymd_hms()
, etc.)
relies on a sparse guesser that takes at most 501 elements from the
supplied character vector in order to identify appropriate formats from
the supplied orders. If you get the error All formats failed to parse
and you are confident that your vector contains valid dates, you should
either set exact
argument to TRUE
or use functions that don't perform
format guessing (fast_strptime()
, parse_date_time2()
or
base::strptime()
).
For performance reasons, when timezone is not UTC,
parse_date_time2()
and fast_strptime()
perform no validity checks for
daylight savings time. Thus, if your input string contains an invalid date
time which falls into DST gap and lt = TRUE
you will get an POSIXlt
object with a non-existent time. If lt = FALSE
your time instant will be
adjusted to a valid time by adding an hour. See examples. If you want to
get NA for invalid date-times use fit_to_timeline()
explicitly.
base::strptime()
, ymd()
, ymd_hms()
## ** orders are much easier to write ** x <- c("09-01-01", "09-01-02", "09-01-03") parse_date_time(x, "ymd") parse_date_time(x, "y m d") parse_date_time(x, "%y%m%d") # "2009-01-01 UTC" "2009-01-02 UTC" "2009-01-03 UTC" ## ** heterogeneous date-times ** x <- c("09-01-01", "090102", "09-01 03", "09-01-03 12:02") parse_date_time(x, c("ymd", "ymd HM")) ## ** different ymd orders ** x <- c("2009-01-01", "02022010", "02-02-2010") parse_date_time(x, c("dmY", "ymd")) ## "2009-01-01 UTC" "2010-02-02 UTC" "2010-02-02 UTC" ## ** truncated time-dates ** x <- c("2011-12-31 12:59:59", "2010-01-01 12:11", "2010-01-01 12", "2010-01-01") parse_date_time(x, "Ymd HMS", truncated = 3) ## ** specifying exact formats and avoiding training and guessing ** parse_date_time(x, c("%m-%d-%y", "%m%d%y", "%m-%d-%y %H:%M"), exact = TRUE) parse_date_time(c('12/17/1996 04:00:00','4/18/1950 0130'), c('%m/%d/%Y %I:%M:%S','%m/%d/%Y %H%M'), exact = TRUE) ## ** quarters and partial dates ** parse_date_time(c("2016.2", "2016-04"), orders = "Yq") parse_date_time(c("2016", "2016-04"), orders = c("Y", "Ym")) ## ** fast parsing ** ## Not run: options(digits.secs = 3) ## random times between 1400 and 3000 tt <- as.character(.POSIXct(runif(1000, -17987443200, 32503680000))) tt <- rep.int(tt, 1000) system.time(out <- as.POSIXct(tt, tz = "UTC")) system.time(out1 <- ymd_hms(tt)) # constant overhead on long vectors system.time(out2 <- parse_date_time2(tt, "YmdHMOS")) system.time(out3 <- fast_strptime(tt, "%Y-%m-%d %H:%M:%OS")) all.equal(out, out1) all.equal(out, out2) all.equal(out, out3) ## End(Not run) ## ** how to use `select_formats` argument ** ## By default %Y has precedence: parse_date_time(c("27-09-13", "27-09-2013"), "dmy") ## to give priority to %y format, define your own select_format function: my_select <- function(trained, drop=FALSE, ...){ n_fmts <- nchar(gsub("[^%]", "", names(trained))) + grepl("%y", names(trained))*1.5 names(trained[ which.max(n_fmts) ]) } parse_date_time(c("27-09-13", "27-09-2013"), "dmy", select_formats = my_select) ## ** invalid times with "fast" parsing ** parse_date_time("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York") parse_date_time2("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York") parse_date_time2("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York", lt = TRUE)
## ** orders are much easier to write ** x <- c("09-01-01", "09-01-02", "09-01-03") parse_date_time(x, "ymd") parse_date_time(x, "y m d") parse_date_time(x, "%y%m%d") # "2009-01-01 UTC" "2009-01-02 UTC" "2009-01-03 UTC" ## ** heterogeneous date-times ** x <- c("09-01-01", "090102", "09-01 03", "09-01-03 12:02") parse_date_time(x, c("ymd", "ymd HM")) ## ** different ymd orders ** x <- c("2009-01-01", "02022010", "02-02-2010") parse_date_time(x, c("dmY", "ymd")) ## "2009-01-01 UTC" "2010-02-02 UTC" "2010-02-02 UTC" ## ** truncated time-dates ** x <- c("2011-12-31 12:59:59", "2010-01-01 12:11", "2010-01-01 12", "2010-01-01") parse_date_time(x, "Ymd HMS", truncated = 3) ## ** specifying exact formats and avoiding training and guessing ** parse_date_time(x, c("%m-%d-%y", "%m%d%y", "%m-%d-%y %H:%M"), exact = TRUE) parse_date_time(c('12/17/1996 04:00:00','4/18/1950 0130'), c('%m/%d/%Y %I:%M:%S','%m/%d/%Y %H%M'), exact = TRUE) ## ** quarters and partial dates ** parse_date_time(c("2016.2", "2016-04"), orders = "Yq") parse_date_time(c("2016", "2016-04"), orders = c("Y", "Ym")) ## ** fast parsing ** ## Not run: options(digits.secs = 3) ## random times between 1400 and 3000 tt <- as.character(.POSIXct(runif(1000, -17987443200, 32503680000))) tt <- rep.int(tt, 1000) system.time(out <- as.POSIXct(tt, tz = "UTC")) system.time(out1 <- ymd_hms(tt)) # constant overhead on long vectors system.time(out2 <- parse_date_time2(tt, "YmdHMOS")) system.time(out3 <- fast_strptime(tt, "%Y-%m-%d %H:%M:%OS")) all.equal(out, out1) all.equal(out, out2) all.equal(out, out3) ## End(Not run) ## ** how to use `select_formats` argument ** ## By default %Y has precedence: parse_date_time(c("27-09-13", "27-09-2013"), "dmy") ## to give priority to %y format, define your own select_format function: my_select <- function(trained, drop=FALSE, ...){ n_fmts <- nchar(gsub("[^%]", "", names(trained))) + grepl("%y", names(trained))*1.5 names(trained[ which.max(n_fmts) ]) } parse_date_time(c("27-09-13", "27-09-2013"), "dmy", select_formats = my_select) ## ** invalid times with "fast" parsing ** parse_date_time("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York") parse_date_time2("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York") parse_date_time2("2010-03-14 02:05:06", "YmdHMS", tz = "America/New_York", lt = TRUE)
period()
creates or parses a period object with the specified values.
period(num = NULL, units = "second", ...) is.period(x) seconds(x = 1) minutes(x = 1) hours(x = 1) days(x = 1) weeks(x = 1) years(x = 1) milliseconds(x = 1) microseconds(x = 1) nanoseconds(x = 1) picoseconds(x = 1) ## S3 method for class 'numeric' months(x, abbreviate)
period(num = NULL, units = "second", ...) is.period(x) seconds(x = 1) minutes(x = 1) hours(x = 1) days(x = 1) weeks(x = 1) years(x = 1) milliseconds(x = 1) microseconds(x = 1) nanoseconds(x = 1) picoseconds(x = 1) ## S3 method for class 'numeric' months(x, abbreviate)
num |
a numeric or character vector. A character vector can specify periods in a convenient shorthand format or ISO 8601 specification. All unambiguous name units and abbreviations are supported, "m" stands for months, "M" for minutes unless ISO 8601 "P" modifier is present (see examples). Fractional units are supported but the fractional part is always converted to seconds. |
units |
a character vector that lists the type of units to be used. The
units in units are matched to the values in num according to their
order. When |
... |
a list of time units to be included in the period and their
amounts. Seconds, minutes, hours, days, weeks, months, and years are
supported. Normally only one of |
x |
Any R object for |
abbreviate |
Ignored. For consistency with S3 generic in base namespace. |
Within a Period object, time units do not have a fixed length (except for seconds) until they are added to a date-time. The length of each time unit will depend on the date-time to which it is added. For example, a year that begins on 2009-01-01 will be 365 days long. A year that begins on 2012-01-01 will be 366 days long. When math is performed with a period object, each unit is applied separately. How the length of a period is distributed among its units is non-trivial. For example, when leap seconds occur 1 minute is longer than 60 seconds.
Periods track the change in the "clock time" between two date-times. They are measured in common time related units: years, months, days, hours, minutes, and seconds. Each unit except for seconds must be expressed in integer values.
Besides the main constructor and parser period()
, period objects can also
be created with the specialized functions years()
, months()
, weeks()
,
days()
, hours()
, minutes()
, and seconds()
. These objects can be added
to and subtracted to date-times to create a user interface similar to object
oriented programming.
Note: Arithmetic with periods can result in undefined behavior when
non-existent dates are involved (such as February 29th in non-leap years).
Please see Period for more details and %m+%
and
add_with_rollback()
for alternative operations.
a period object
Period, period()
, %m+%
,
add_with_rollback()
### Separate period and units vectors period(c(90, 5), c("second", "minute")) # "5M 90S" period(-1, "days") period(c(3, 1, 2, 13, 1), c("second", "minute", "hour", "day", "week")) period(c(1, -60), c("hour", "minute")) period(0, "second") ### Units as arguments period(second = 90, minute = 5) period(day = -1) period(second = 3, minute = 1, hour = 2, day = 13, week = 1) period(hour = 1, minute = -60) period(second = 0) period(c(1, -60), c("hour", "minute"), hour = c(1, 2), minute = c(3, 4)) ### Lubridate style parsing period("2M 1sec") period("2hours 2minutes 1second") period("2d 2H 2M 2S") period("2days 2hours 2mins 2secs") period("2 days, 2 hours, 2 mins, 2 secs") # Missing numerals default to 1. Repeated units are added up. period("day day") ### ISO 8601 parsing period("P10M23DT23H") # M stands for months period("10DT10M") # M stands for minutes period("P3Y6M4DT12H30M5S") # M for both minutes and months period("P23DT60H 20min 100 sec") # mixing ISO and lubridate style parsing ### Comparison with characters (from v1.6.0) period("day 2 sec") > "day 1sec" ### Elementary Constructors x <- ymd("2009-08-03") x + days(1) + hours(6) + minutes(30) x + days(100) - hours(8) class(as.Date("2009-08-09") + days(1)) # retains Date class as.Date("2009-08-09") + hours(12) class(as.Date("2009-08-09") + hours(12)) # converts to POSIXt class to accomodate time units years(1) - months(7) c(1:3) * hours(1) hours(1:3) # sequencing y <- ymd(090101) # "2009-01-01 CST" y + months(0:11) # compare DST handling to durations boundary <- ymd_hms("2009-03-08 01:59:59", tz = "America/Chicago") boundary + days(1) # period boundary + ddays(1) # duration is.period(as.Date("2009-08-03")) # FALSE is.period(period(months = 1, days = 15)) # TRUE
### Separate period and units vectors period(c(90, 5), c("second", "minute")) # "5M 90S" period(-1, "days") period(c(3, 1, 2, 13, 1), c("second", "minute", "hour", "day", "week")) period(c(1, -60), c("hour", "minute")) period(0, "second") ### Units as arguments period(second = 90, minute = 5) period(day = -1) period(second = 3, minute = 1, hour = 2, day = 13, week = 1) period(hour = 1, minute = -60) period(second = 0) period(c(1, -60), c("hour", "minute"), hour = c(1, 2), minute = c(3, 4)) ### Lubridate style parsing period("2M 1sec") period("2hours 2minutes 1second") period("2d 2H 2M 2S") period("2days 2hours 2mins 2secs") period("2 days, 2 hours, 2 mins, 2 secs") # Missing numerals default to 1. Repeated units are added up. period("day day") ### ISO 8601 parsing period("P10M23DT23H") # M stands for months period("10DT10M") # M stands for minutes period("P3Y6M4DT12H30M5S") # M for both minutes and months period("P23DT60H 20min 100 sec") # mixing ISO and lubridate style parsing ### Comparison with characters (from v1.6.0) period("day 2 sec") > "day 1sec" ### Elementary Constructors x <- ymd("2009-08-03") x + days(1) + hours(6) + minutes(30) x + days(100) - hours(8) class(as.Date("2009-08-09") + days(1)) # retains Date class as.Date("2009-08-09") + hours(12) class(as.Date("2009-08-09") + hours(12)) # converts to POSIXt class to accomodate time units years(1) - months(7) c(1:3) * hours(1) hours(1:3) # sequencing y <- ymd(090101) # "2009-01-01 CST" y + months(0:11) # compare DST handling to durations boundary <- ymd_hms("2009-03-08 01:59:59", tz = "America/Chicago") boundary + days(1) # period boundary + ddays(1) # duration is.period(as.Date("2009-08-03")) # FALSE is.period(period(months = 1, days = 15)) # TRUE
period_to_seconds()
approximately converts a period to seconds assuming
there are 365.25 days in a calendar year and 365.25/12 days in a month.
seconds_to_period()
create a period that has the maximum number of
non-zero elements (days, hours, minutes, seconds). This computation is exact
because it doesn't involve years or months.
period_to_seconds(x) seconds_to_period(x)
period_to_seconds(x) seconds_to_period(x)
x |
A numeric object. The number of seconds to coerce into a period. |
A number (period) that roughly equates to the period (seconds) given.
pretty.dates indentifies which unit of time the sub-intervals should be measured in to provide approximately n breaks. It then chooses a "pretty" length for the sub-intervals and sets start and endpoints that 1) span the entire range of the data, and 2) allow the breaks to occur on important date-times (i.e. on the hour, on the first of the month, etc.)
pretty_dates(x, n, ...)
pretty_dates(x, n, ...)
x |
a vector of POSIXct, POSIXlt, Date, or chron date-time objects |
n |
integer value of the desired number of breaks |
... |
additional arguments to pass to function |
a vector of date-times that can be used as axis tick marks or bin breaks
x <- seq.Date(as.Date("2009-08-02"), by = "year", length.out = 2) pretty_dates(x, 12)
x <- seq.Date(as.Date("2009-08-02"), by = "year", length.out = 2) pretty_dates(x, 12)
Quarters divide the year into fourths. Semesters divide the year into halfs.
quarter( x, type = "quarter", fiscal_start = 1, with_year = identical(type, "year.quarter") ) semester(x, with_year = FALSE)
quarter( x, type = "quarter", fiscal_start = 1, with_year = identical(type, "year.quarter") ) semester(x, with_year = FALSE)
x |
a date-time object of class POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, fts or anything else that can be converted with as.POSIXlt |
type |
the format to be returned for the quarter. Can be one one of "quarter" - return numeric quarter (default), "year.quarter" return the ending year and quarter as a number of the form year.quarter, "date_first" or "date_last" - return the date at the quarter's start or end, "year_start/end" - return a full description of the quarter as a string which includes the start and end of the year (ex. "2020/21 Q1"). |
fiscal_start |
numeric indicating the starting month of a fiscal year. |
with_year |
logical indicating whether or not to include the quarter or
semester's year (deprecated; use the |
numeric or a vector of class POSIXct if type
argument is date_first
or
date_last
. When type
is year.quarter
the year returned is the end year of the
financial year.
x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31")) quarter(x) quarter(x, type = "year.quarter") quarter(x, type = "year.quarter", fiscal_start = 11) quarter(x, type = "date_first", fiscal_start = 11) quarter(x, type = "date_last", fiscal_start = 11) semester(x) semester(x, with_year = TRUE)
x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31")) quarter(x) quarter(x, type = "year.quarter") quarter(x, type = "year.quarter", fiscal_start = 11) quarter(x, type = "date_first", fiscal_start = 11) quarter(x, type = "date_last", fiscal_start = 11) semester(x) semester(x, with_year = TRUE)
rollbackward()
changes a date to the last day of the previous month or to
the first day of the month. rollforward()
rolls to the last day of the
current month or to the first day of the next month. Optionally, the new date
can retain the same hour, minute, and second information. rollback()
is a
synonym for rollbackward()
.
rollbackward(dates, roll_to_first = FALSE, preserve_hms = TRUE) rollback(dates, roll_to_first = FALSE, preserve_hms = TRUE) rollforward(dates, roll_to_first = FALSE, preserve_hms = TRUE)
rollbackward(dates, roll_to_first = FALSE, preserve_hms = TRUE) rollback(dates, roll_to_first = FALSE, preserve_hms = TRUE) rollforward(dates, roll_to_first = FALSE, preserve_hms = TRUE)
dates |
A POSIXct, POSIXlt or Date class object. |
roll_to_first |
Rollback to the first day of the month instead of the last day of the month |
preserve_hms |
Retains the same hour, minute, and second information? If FALSE, the new date will be at 00:00:00. |
A date-time object of class POSIXlt, POSIXct or Date, whose day has been adjusted to the last day of the previous month, or to the first day of the month.
date <- ymd("2010-03-03") rollbackward(date) dates <- date + months(0:2) rollbackward(dates) date <- ymd_hms("2010-03-03 12:44:22") rollbackward(date) rollbackward(date, roll_to_first = TRUE) rollbackward(date, preserve_hms = FALSE) rollbackward(date, roll_to_first = TRUE, preserve_hms = FALSE)
date <- ymd("2010-03-03") rollbackward(date) dates <- date + months(0:2) rollbackward(dates) date <- ymd_hms("2010-03-03 12:44:22") rollbackward(date) rollbackward(date, roll_to_first = TRUE) rollbackward(date, preserve_hms = FALSE) rollbackward(date, roll_to_first = TRUE, preserve_hms = FALSE)
round_date()
takes a date-time object and time unit, and rounds it to the nearest value
of the specified time unit. For rounding date-times which are exactly halfway
between two consecutive units, the convention is to round up. Note that this
is in line with the behavior of R's base::round.POSIXt()
function
but does not follow the convention of the base base::round()
function
which "rounds to the even digit", as per IEC 60559.
Rounding to the nearest unit or multiple of a unit is supported. All meaningful specifications in the English language are supported - secs, min, mins, 2 minutes, 3 years etc.
Rounding to fractional seconds is also supported. Please note that rounding to fractions smaller than 1 second can lead to large precision errors due to the floating point representation of the POSIXct objects. See examples.
floor_date()
takes a date-time object and rounds it down to the nearest
boundary of the specified time unit.
ceiling_date()
takes a date-time object and rounds it up to the nearest
boundary of the specified time unit.
round_date( x, unit = "second", week_start = getOption("lubridate.week.start", 7) ) floor_date( x, unit = "seconds", week_start = getOption("lubridate.week.start", 7) ) ceiling_date( x, unit = "seconds", change_on_boundary = NULL, week_start = getOption("lubridate.week.start", 7) )
round_date( x, unit = "second", week_start = getOption("lubridate.week.start", 7) ) floor_date( x, unit = "seconds", week_start = getOption("lubridate.week.start", 7) ) ceiling_date( x, unit = "seconds", change_on_boundary = NULL, week_start = getOption("lubridate.week.start", 7) )
x |
a vector of date-time objects |
unit |
a string, When When |
week_start |
week start day (Default is 7, Sunday. Set |
change_on_boundary |
if this is |
In lubridate, functions that round date-time objects try to preserve the class of the input object whenever possible. This is done by first rounding to an instant, and then converting to the original class as per usual R conventions.
When unit
is a string, return a Date object if x
is a Date and
unit
is larger or equal than "day", otherwise a POSIXct object. When
unit
is a date-time object, return a date-time object of the same class
and same time zone as unit
.
By default, rounding up Date
objects follows 3 steps:
Convert to an instant representing lower bound of the Date:
2000-01-01
–> 2000-01-01 00:00:00
Round up to the next closest rounding unit boundary. For example,
if the rounding unit is month
then next closest boundary of 2000-01-01
is 2000-02-01 00:00:00
.
The motivation for this is that the "partial" 2000-01-01
is conceptually
an interval (2000-01-01 00:00:00
– 2000-01-02 00:00:00
) and the day
hasn't started clocking yet at the exact boundary 00:00:00
. Thus, it
seems wrong to round a day to its lower boundary.
Behavior on the boundary can be changed by setting
change_on_boundary
to TRUE
or FALSE
.
If the rounding unit is smaller than a day, return the instant from step 2
(POSIXct
), otherwise convert to and return a Date
object.
## print fractional seconds options(digits.secs = 6) x <- ymd_hms("2009-08-03 12:01:59.23") round_date(x, ".5s") round_date(x, "sec") round_date(x, "second") round_date(x, "minute") round_date(x, "5 mins") round_date(x, "hour") round_date(x, "2 hours") round_date(x, "day") round_date(x, "week") round_date(x, "month") round_date(x, "bimonth") round_date(x, "quarter") == round_date(x, "3 months") round_date(x, "halfyear") round_date(x, "year") x <- ymd_hms("2009-08-03 12:01:59.23") floor_date(x, ".1s") floor_date(x, "second") floor_date(x, "minute") floor_date(x, "hour") floor_date(x, "day") floor_date(x, "week") floor_date(x, "month") floor_date(x, "bimonth") floor_date(x, "quarter") floor_date(x, "season") floor_date(x, "halfyear") floor_date(x, "year") x <- ymd_hms("2009-08-03 12:01:59.23") ceiling_date(x, ".1 sec") # imprecise representation at 0.1 sec !!! ceiling_date(x, "second") ceiling_date(x, "minute") ceiling_date(x, "5 mins") ceiling_date(x, "hour") ceiling_date(x, "day") ceiling_date(x, "week") ceiling_date(x, "month") ceiling_date(x, "bimonth") == ceiling_date(x, "2 months") ceiling_date(x, "quarter") ceiling_date(x, "season") ceiling_date(x, "halfyear") ceiling_date(x, "year") ## Period unit argument floor_date(x, days(2)) floor_date(x, years(1)) ## As of R 3.4.2 POSIXct printing of fractional numbers is wrong as.POSIXct("2009-08-03 12:01:59.3") ## -> "2009-08-03 12:01:59.2 CEST" ceiling_date(x, ".1 sec") ## -> "2009-08-03 12:01:59.2 CEST" ## behaviour of `change_on_boundary` ## As per default behaviour `NULL`, instants on the boundary remain the ## same but dates are rounded up ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month") ceiling_date(ymd("2000-01-01"), "month") ## If `TRUE`, both instants and dates on the boundary are rounded up ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month", change_on_boundary = TRUE) ceiling_date(ymd("2000-01-01"), "month") ## If `FALSE`, both instants and dates on the boundary remain the same ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month", change_on_boundary = FALSE) ceiling_date(ymd("2000-01-01"), "month") x <- ymd_hms("2000-01-01 00:00:00") ceiling_date(x, "month") ceiling_date(x, "month", change_on_boundary = TRUE) ## For Date objects first day of the month is not on the ## "boundary". change_on_boundary applies to instants only. x <- ymd("2000-01-01") ceiling_date(x, "month") ceiling_date(x, "month", change_on_boundary = TRUE)
## print fractional seconds options(digits.secs = 6) x <- ymd_hms("2009-08-03 12:01:59.23") round_date(x, ".5s") round_date(x, "sec") round_date(x, "second") round_date(x, "minute") round_date(x, "5 mins") round_date(x, "hour") round_date(x, "2 hours") round_date(x, "day") round_date(x, "week") round_date(x, "month") round_date(x, "bimonth") round_date(x, "quarter") == round_date(x, "3 months") round_date(x, "halfyear") round_date(x, "year") x <- ymd_hms("2009-08-03 12:01:59.23") floor_date(x, ".1s") floor_date(x, "second") floor_date(x, "minute") floor_date(x, "hour") floor_date(x, "day") floor_date(x, "week") floor_date(x, "month") floor_date(x, "bimonth") floor_date(x, "quarter") floor_date(x, "season") floor_date(x, "halfyear") floor_date(x, "year") x <- ymd_hms("2009-08-03 12:01:59.23") ceiling_date(x, ".1 sec") # imprecise representation at 0.1 sec !!! ceiling_date(x, "second") ceiling_date(x, "minute") ceiling_date(x, "5 mins") ceiling_date(x, "hour") ceiling_date(x, "day") ceiling_date(x, "week") ceiling_date(x, "month") ceiling_date(x, "bimonth") == ceiling_date(x, "2 months") ceiling_date(x, "quarter") ceiling_date(x, "season") ceiling_date(x, "halfyear") ceiling_date(x, "year") ## Period unit argument floor_date(x, days(2)) floor_date(x, years(1)) ## As of R 3.4.2 POSIXct printing of fractional numbers is wrong as.POSIXct("2009-08-03 12:01:59.3") ## -> "2009-08-03 12:01:59.2 CEST" ceiling_date(x, ".1 sec") ## -> "2009-08-03 12:01:59.2 CEST" ## behaviour of `change_on_boundary` ## As per default behaviour `NULL`, instants on the boundary remain the ## same but dates are rounded up ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month") ceiling_date(ymd("2000-01-01"), "month") ## If `TRUE`, both instants and dates on the boundary are rounded up ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month", change_on_boundary = TRUE) ceiling_date(ymd("2000-01-01"), "month") ## If `FALSE`, both instants and dates on the boundary remain the same ceiling_date(ymd_hms("2000-01-01 00:00:00"), "month", change_on_boundary = FALSE) ceiling_date(ymd("2000-01-01"), "month") x <- ymd_hms("2000-01-01 00:00:00") ceiling_date(x, "month") ceiling_date(x, "month", change_on_boundary = TRUE) ## For Date objects first day of the month is not on the ## "boundary". change_on_boundary applies to instants only. x <- ymd("2000-01-01") ceiling_date(x, "month") ceiling_date(x, "month", change_on_boundary = TRUE)
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
second(x) second(x) <- value
second(x) second(x) <- value
x |
a date-time object |
value |
numeric value to be assigned |
the seconds element of x as a decimal number
x <- ymd("2012-03-26") second(x) second(x) <- 1 second(x) <- 61 second(x) > 2
x <- ymd("2012-03-26") second(x) second(x) <- 1 second(x) <- 61 second(x) > 2
Stamps are just like format()
, but based on human-friendly
templates like "Recorded at 10 am, September 2002" or "Meeting, Sunday May
1, 2000, at 10:20 pm".
stamp( x, orders = lubridate_formats, locale = Sys.getlocale("LC_TIME"), quiet = FALSE, exact = FALSE ) stamp_date(x, locale = Sys.getlocale("LC_TIME"), quiet = FALSE) stamp_time(x, locale = Sys.getlocale("LC_TIME"), quiet = FALSE)
stamp( x, orders = lubridate_formats, locale = Sys.getlocale("LC_TIME"), quiet = FALSE, exact = FALSE ) stamp_date(x, locale = Sys.getlocale("LC_TIME"), quiet = FALSE) stamp_time(x, locale = Sys.getlocale("LC_TIME"), quiet = FALSE)
x |
a character vector of templates. |
orders |
orders are sequences of formatting characters which might be
used for disambiguation. For example "ymd hms", "aym" etc. See
|
locale |
locale in which |
quiet |
whether to output informative messages. |
exact |
logical. If |
stamp()
is a stamping function date-time templates mainly, though it
correctly handles all date and time formats as long as they are
unambiguous. stamp_date()
, and stamp_time()
are the specialized
stamps for dates and times (MHS). These function might be useful when the
input template is unambiguous and matches both a time and a date format.
Lubridate tries hard to guess the formats, but often a given format can be
interpreted in multiple ways. One way to deal with such cases is to provide
unambiguous formats like 22/05/81 instead of 10/05/81 for d/m/y
format. Another way is to use a more specialized stamp_date
and
stamp_time
. The core function stamp()
prioritizes longer date-time
formats.
If x
is a vector of values lubridate will choose the format which
"fits" x
the best. Note that longer formats are preferred. If you have
"22:23:00 PM" then "HMSp" format will be given priority to shorter "HMS"
order which also fits the supplied string.
Finally, you can give desired format order directly as orders
argument.
a function to be applied on a vector of dates
guess_formats()
, parse_date_time()
, strptime()
D <- ymd("2010-04-05") - days(1:5) stamp("March 1, 1999")(D) sf <- stamp("Created on Sunday, Jan 1, 1999 3:34 pm") sf(D) stamp("Jan 01")(D) stamp("Sunday, May 1, 2000", locale = "C")(D) stamp("Sun Aug 5")(D) #=> "Sun Aug 04" "Sat Aug 04" "Fri Aug 04" "Thu Aug 04" "Wed Aug 03" stamp("12/31/99")(D) #=> "06/09/11" stamp("Sunday, May 1, 2000 22:10", locale = "C")(D) stamp("2013-01-01T06:00:00Z")(D) stamp("2013-01-01T00:00:00-06")(D) stamp("2013-01-01T00:00:00-08:00")(force_tz(D, "America/Chicago"))
D <- ymd("2010-04-05") - days(1:5) stamp("March 1, 1999")(D) sf <- stamp("Created on Sunday, Jan 1, 1999 3:34 pm") sf(D) stamp("Jan 01")(D) stamp("Sunday, May 1, 2000", locale = "C")(D) stamp("Sun Aug 5")(D) #=> "Sun Aug 04" "Sat Aug 04" "Fri Aug 04" "Thu Aug 04" "Wed Aug 03" stamp("12/31/99")(D) #=> "06/09/11" stamp("Sunday, May 1, 2000 22:10", locale = "C")(D) stamp("2013-01-01T06:00:00Z")(D) stamp("2013-01-01T00:00:00-06")(D) stamp("2013-01-01T00:00:00-08:00")(force_tz(D, "America/Chicago"))
Compute the exact length of a time span
time_length(x, unit = "second") ## S4 method for signature 'Interval' time_length(x, unit = "second")
time_length(x, unit = "second") ## S4 method for signature 'Interval' time_length(x, unit = "second")
x |
a duration, period, difftime or interval |
unit |
a character string that specifies with time units to use |
When x
is an Interval object and
unit
are years or months, time_length()
takes into account
the fact that all months and years don't have the same number of days.
When x
is a Duration, Period
or difftime()
object, length in months or years is based on their
most common lengths in seconds (see timespan()
).
the length of the interval in the specified unit. A negative number connotes a negative interval or duration
int <- interval(ymd("1980-01-01"), ymd("2014-09-18")) time_length(int, "week") # Exact age time_length(int, "year") # Age at last anniversary trunc(time_length(int, "year")) # Example of difference between intervals and durations int <- interval(ymd("1900-01-01"), ymd("1999-12-31")) time_length(int, "year") time_length(as.duration(int), "year")
int <- interval(ymd("1980-01-01"), ymd("2014-09-18")) time_length(int, "week") # Exact age time_length(int, "year") # Age at last anniversary trunc(time_length(int, "year")) # Example of difference between intervals and durations int <- interval(ymd("1900-01-01"), ymd("1999-12-31")) time_length(int, "year") time_length(as.duration(int), "year")
A time span can be measured in three ways: as a duration, an interval, or a period.
durations record the exact number of seconds in a time span. They measure the exact passage of time but do not always align with human measurements like hours, months and years.
periods record the change in the clock time between two date-times. They are measured in human units: years, months, days, hours, minutes, and seconds.
intervals are time spans bound by two real date-times. Intervals can be accurately converted to periods and durations.
duration(3690, "seconds") period(3690, "seconds") period(second = 30, minute = 1, hour = 1) interval(ymd_hms("2009-08-09 13:01:30"), ymd_hms("2009-08-09 12:00:00")) date <- ymd_hms("2009-03-08 01:59:59") # DST boundary date + days(1) date + ddays(1) date2 <- ymd_hms("2000-02-29 12:00:00") date2 + years(1) # self corrects to next real day date3 <- ymd_hms("2009-01-31 01:00:00") date3 + c(0:11) * months(1) span <- date2 %--% date # creates interval date <- ymd_hms("2009-01-01 00:00:00") date + years(1) date - days(3) + hours(6) date + 3 * seconds(10) months(6) + days(1)
duration(3690, "seconds") period(3690, "seconds") period(second = 30, minute = 1, hour = 1) interval(ymd_hms("2009-08-09 13:01:30"), ymd_hms("2009-08-09 12:00:00")) date <- ymd_hms("2009-03-08 01:59:59") # DST boundary date + days(1) date + ddays(1) date2 <- ymd_hms("2000-02-29 12:00:00") date2 + years(1) # self corrects to next real day date3 <- ymd_hms("2009-01-31 01:00:00") date3 + c(0:11) * months(1) span <- date2 %--% date # creates interval date <- ymd_hms("2009-01-01 00:00:00") date + years(1) date - days(3) + hours(6) date + 3 * seconds(10) months(6) + days(1)
Conveniently get and set the time zone of a date-time.
tz<-
is an alias for force_tz()
, which preserves the local time,
creating a different instant in time. Use with_tz()
if you want keep
the instant the same, but change the printed representation.
tz(x) tz(x) <- value
tz(x) tz(x) <- value
x |
A date-time vector, usually of class |
value |
New value of time zone. |
A character vector of length 1. An empty string (""
) represents
your current time zone.
For backward compatibility, the time zone of a date, NA
, or
character vector is "UTC"
.
Time zones are stored in system specific database, so are not guaranteed
to be the same on every system (however, they are usually pretty similar
unless your system is very out of date). You can see a complete list with
OlsonNames()
.
See DateTimeClasses for a description of the underlying
tzone
attribute..
x <- y <- ymd_hms("2012-03-26 10:10:00", tz = "UTC") tz(x) # Note that setting tz() preserved the clock time, which implies # that the actual instant in time is changing tz(y) <- "Pacific/Auckland" y x - y # This is the same as force_tz() force_tz(x, "Pacific/Auckland") # Use with_tz() if you want to change the time zone, leave # the instant in time the same with_tz(x, "Pacific/Auckland")
x <- y <- ymd_hms("2012-03-26 10:10:00", tz = "UTC") tz(x) # Note that setting tz() preserved the clock time, which implies # that the actual instant in time is changing tz(y) <- "Pacific/Auckland" y x - y # This is the same as force_tz() force_tz(x, "Pacific/Auckland") # Use with_tz() if you want to change the time zone, leave # the instant in time the same with_tz(x, "Pacific/Auckland")
week()
returns the number of complete seven day periods that have
occurred between the date and January 1st, plus one.
isoweek()
returns the week as it would appear in the ISO 8601
system, which uses a reoccurring leap week.
epiweek()
is the US CDC version of epidemiological week. It
follows same rules as isoweek()
but starts on Sunday. In other parts of
the world the convention is to start epidemiological weeks on Monday,
which is the same as isoweek
.
week(x) week(x) <- value isoweek(x) epiweek(x)
week(x) week(x) <- value isoweek(x) epiweek(x)
x |
a date-time object. Must be a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, or fts object. |
value |
a numeric object |
the weeks element of x as an integer number
https://en.wikipedia.org/wiki/ISO_week_date
x <- ymd("2012-03-26") week(x) week(x) <- 1 week(x) <- 54 week(x) > 3
x <- ymd("2012-03-26") week(x) week(x) <- 1 week(x) <- 54 week(x) > 3
with_tz returns a date-time as it would appear in a different time zone.
The actual moment of time measured does not change, just the time zone it is
measured in. with_tz defaults to the Universal Coordinated time zone (UTC)
when an unrecognized time zone is inputted. See Sys.timezone()
for more information on how R recognizes time zones.
with_tz(time, tzone = "", ...) ## Default S3 method: with_tz(time, tzone = "", ...)
with_tz(time, tzone = "", ...) ## Default S3 method: with_tz(time, tzone = "", ...)
time |
a POSIXct, POSIXlt, Date, chron date-time object or a data.frame
object. When a data.frame all POSIXt elements of a data.frame are processed
with |
tzone |
a character string containing the time zone to convert to. R must recognize the name contained in the string as a time zone on your system. |
... |
Parameters passed to other methods. |
a POSIXct object in the updated time zone
x <- ymd_hms("2009-08-07 00:00:01", tz = "America/New_York") with_tz(x, "GMT")
x <- ymd_hms("2009-08-07 00:00:01", tz = "America/New_York") with_tz(x, "GMT")
Date-time must be a POSIXct, POSIXlt, Date, Period or any other object convertible to POSIXlt.
isoyear()
returns years according to the ISO 8601 week calendar.
epiyear()
returns years according to the epidemiological week calendars.
year(x) year(x) <- value isoyear(x) epiyear(x)
year(x) year(x) <- value isoyear(x) epiyear(x)
x |
a date-time object |
value |
a numeric object |
year does not yet support years before 0 C.E.
the years element of x as a decimal number
https://en.wikipedia.org/wiki/ISO_week_date
x <- ymd("2012-03-26") year(x) year(x) <- 2001 year(x) > 1995
x <- ymd("2012-03-26") year(x) year(x) <- 2001 year(x) > 1995
Transforms dates stored in character and numeric vectors to Date or POSIXct
objects (see tz
argument). These functions recognize arbitrary
non-digit separators as well as no separator. As long as the order of
formats is correct, these functions will parse dates correctly even when the
input vectors contain differently formatted dates. See examples.
ymd( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) myd( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dym( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) yq(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME")) ym(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME")) my(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"))
ymd( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) myd( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dym( ..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"), truncated = 0 ) yq(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME")) ym(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME")) my(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"))
... |
a character or numeric vector of suspected dates |
quiet |
logical. If |
tz |
Time zone indicator. If |
locale |
locale to be used, see locales. On Linux systems you
can use |
truncated |
integer. Number of formats that can be truncated. |
In case of heterogeneous date formats, the ymd()
family guesses formats based
on a subset of the input vector. If the input vector contains many missing
values or non-date strings, the subset might not contain meaningful dates
and the date-time format won't be guessed resulting in
All formats failed to parse
error. In such cases please see
parse_date_time()
for a more flexible parsing interface.
If the truncated
parameter is non-zero, the ymd()
functions also check for
truncated formats. For example, ymd()
with truncated = 2
will also
parse incomplete dates like 2012-06
and 2012
.
NOTE: The ymd()
family of functions is based on parse_date_time()
and thus
directly drop to the internal C parser for numeric months, but uses
base::strptime()
for alphabetic months. This implies that some of base::strptime()
's
limitations are inherited by lubridate's parser. For example, truncated
formats (like %Y-%b
) will not be parsed. Numeric truncated formats (like
%Y-%m
) are handled correctly by lubridate's C parser.
As of version 1.3.0, lubridate's parse functions no longer return a
message that displays which format they used to parse their input. You can
change this by setting the lubridate.verbose
option to TRUE
with
options(lubridate.verbose = TRUE)
.
a vector of class POSIXct if tz
argument is non-NULL
or Date if tz
is NULL
(default)
parse_date_time()
for an even more flexible low level
mechanism.
x <- c("09-01-01", "09-01-02", "09-01-03") ymd(x) x <- c("2009-01-01", "2009-01-02", "2009-01-03") ymd(x) ymd(090101, 90102) now() > ymd(20090101) ## TRUE dmy(010210) mdy(010210) yq('2014.2') ## heterogeneous formats in a single vector: x <- c(20090101, "2009-01-02", "2009 01 03", "2009-1-4", "2009-1, 5", "Created on 2009 1 6", "200901 !!! 07") ymd(x) ## What lubridate might not handle: ## Extremely weird cases when one of the separators is "" and some of the ## formats are not in double digits might not be parsed correctly: ## Not run: ymd("201002-01", "201002-1", "20102-1") dmy("0312-2010", "312-2010") ## End(Not run)
x <- c("09-01-01", "09-01-02", "09-01-03") ymd(x) x <- c("2009-01-01", "2009-01-02", "2009-01-03") ymd(x) ymd(090101, 90102) now() > ymd(20090101) ## TRUE dmy(010210) mdy(010210) yq('2014.2') ## heterogeneous formats in a single vector: x <- c(20090101, "2009-01-02", "2009 01 03", "2009-1-4", "2009-1, 5", "Created on 2009 1 6", "200901 !!! 07") ymd(x) ## What lubridate might not handle: ## Extremely weird cases when one of the separators is "" and some of the ## formats are not in double digits might not be parsed correctly: ## Not run: ymd("201002-01", "201002-1", "20102-1") dmy("0312-2010", "312-2010") ## End(Not run)
Transform dates stored as character or numeric vectors to POSIXct
objects. The ymd_hms()
family of functions recognizes all non-alphanumeric
separators (with the exception of "." if frac = TRUE
) and correctly
handles heterogeneous date-time representations. For more flexibility in
treatment of heterogeneous formats, see low level parser
parse_date_time()
.
ymd_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ymd_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ymd_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 )
ymd_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ymd_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ymd_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) dmy_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) mdy_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_hms( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_hm( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 ) ydm_h( ..., quiet = FALSE, tz = "UTC", locale = Sys.getlocale("LC_TIME"), truncated = 0 )
... |
a character vector of dates in year, month, day, hour, minute, second format |
quiet |
logical. If |
tz |
a character string that specifies which time zone to parse the date with. The string must be a time zone that is recognized by the user's OS. |
locale |
locale to be used, see locales. On Linux systems you
can use |
truncated |
integer, indicating how many formats can be missing. See details. |
The ymd_hms()
functions automatically assign the Universal Coordinated Time
Zone (UTC) to the parsed date. This time zone can be changed with
force_tz()
.
The most common type of irregularity in date-time data is the truncation
due to rounding or unavailability of the time stamp. If the truncated
parameter is non-zero, the ymd_hms()
functions also check for truncated
formats. For example, ymd_hms()
with truncated = 3
will also parse
incomplete dates like 2012-06-01 12:23
, 2012-06-01 12
and
2012-06-01
. NOTE: The ymd()
family of functions is based on
base::strptime()
which currently fails to parse %y-%m
formats.
In case of heterogeneous date formats the ymd_hms()
family guesses formats
based on a subset of the input vector. If the input vector contains many
missing values or non-date strings, the subset might not contain meaningful
dates and the date-time format won't be guessed resulting in
All formats failed to parse
error. In such cases please see
parse_date_time()
for a more flexible parsing interface.
As of version 1.3.0, lubridate's parse functions no longer return a
message that displays which format they used to parse their input. You can
change this by setting the lubridate.verbose
option to TRUE
with
options(lubridate.verbose = TRUE)
.
a vector of POSIXct date-time objects
parse_date_time()
for the underlying mechanism
x <- c("2010-04-14-04-35-59", "2010-04-01-12-00-00") ymd_hms(x) x <- c("2011-12-31 12:59:59", "2010-01-01 12:00:00") ymd_hms(x) ## ** heterogeneous formats ** x <- c(20100101120101, "2009-01-02 12-01-02", "2009.01.03 12:01:03", "2009-1-4 12-1-4", "2009-1, 5 12:1, 5", "200901-08 1201-08", "2009 arbitrary 1 non-decimal 6 chars 12 in between 1 !!! 6", "OR collapsed formats: 20090107 120107 (as long as prefixed with zeros)", "Automatic wday, Thu, detection, 10-01-10 10:01:10 and p format: AM", "Created on 10-01-11 at 10:01:11 PM") ymd_hms(x) ## ** fractional seconds ** op <- options(digits.secs=3) dmy_hms("20/2/06 11:16:16.683") options(op) ## ** different formats for ISO8601 timezone offset ** ymd_hms(c("2013-01-24 19:39:07.880-0600", "2013-01-24 19:39:07.880", "2013-01-24 19:39:07.880-06:00", "2013-01-24 19:39:07.880-06", "2013-01-24 19:39:07.880Z")) ## ** internationalization ** ## Not run: x_RO <- "Ma 2012 august 14 11:28:30 " ymd_hms(x_RO, locale = "ro_RO.utf8") ## End(Not run) ## ** truncated time-dates ** x <- c("2011-12-31 12:59:59", "2010-01-01 12:11", "2010-01-01 12", "2010-01-01") ymd_hms(x, truncated = 3) x <- c("2011-12-31 12:59", "2010-01-01 12", "2010-01-01") ymd_hm(x, truncated = 2) ## ** What lubridate might not handle ** ## Extremely weird cases when one of the separators is "" and some of the ## formats are not in double digits might not be parsed correctly: ## Not run: ymd_hm("20100201 07-01", "20100201 07-1", "20100201 7-01") ## End(Not run)
x <- c("2010-04-14-04-35-59", "2010-04-01-12-00-00") ymd_hms(x) x <- c("2011-12-31 12:59:59", "2010-01-01 12:00:00") ymd_hms(x) ## ** heterogeneous formats ** x <- c(20100101120101, "2009-01-02 12-01-02", "2009.01.03 12:01:03", "2009-1-4 12-1-4", "2009-1, 5 12:1, 5", "200901-08 1201-08", "2009 arbitrary 1 non-decimal 6 chars 12 in between 1 !!! 6", "OR collapsed formats: 20090107 120107 (as long as prefixed with zeros)", "Automatic wday, Thu, detection, 10-01-10 10:01:10 and p format: AM", "Created on 10-01-11 at 10:01:11 PM") ymd_hms(x) ## ** fractional seconds ** op <- options(digits.secs=3) dmy_hms("20/2/06 11:16:16.683") options(op) ## ** different formats for ISO8601 timezone offset ** ymd_hms(c("2013-01-24 19:39:07.880-0600", "2013-01-24 19:39:07.880", "2013-01-24 19:39:07.880-06:00", "2013-01-24 19:39:07.880-06", "2013-01-24 19:39:07.880Z")) ## ** internationalization ** ## Not run: x_RO <- "Ma 2012 august 14 11:28:30 " ymd_hms(x_RO, locale = "ro_RO.utf8") ## End(Not run) ## ** truncated time-dates ** x <- c("2011-12-31 12:59:59", "2010-01-01 12:11", "2010-01-01 12", "2010-01-01") ymd_hms(x, truncated = 3) x <- c("2011-12-31 12:59", "2010-01-01 12", "2010-01-01") ymd_hm(x, truncated = 2) ## ** What lubridate might not handle ** ## Extremely weird cases when one of the separators is "" and some of the ## formats are not in double digits might not be parsed correctly: ## Not run: ymd_hm("20100201 07-01", "20100201 07-1", "20100201 7-01") ## End(Not run)