Reputation: 5512
I have times in this format:
t <- "4/2/2004 12:45"
I can extract day and month using these two lines:
strptime(t, "%m/%d/%Y %H:%M", tz="UTC")$day
strptime(t, "%m/%d/%Y %H:%M", tz="UTC")$mday
But this doesn't give me the years I want. I gives me year without the century:
strptime(t, "%m/%d/%Y %H:%M", tz="UTC")$year
How can I get the year exactly? Like 1987, 2012 etc. And not 87 and 12.
If there is any other function to use for this, I am OK with that as well.
Upvotes: 3
Views: 3112
Reputation: 973
Using base package:
t <- "4/2/2004 12:45"
as.numeric(format(as.Date(t, "%m/%d/%Y %H:%M", tz="UTC"), "%Y"))
result is:
[1] 2004
Upvotes: 3
Reputation: 933
Use lubridate
for all your intuitive timestamp processing needs:
library(lubridate)
t <- "4/2/2004 12:45"
t2 <- mdy_hm(t) # parsing format: month-day-year_hour-minute
day(t2)
yday(t2)
year(t2)
Upvotes: 3
Reputation: 176648
Add 1900. See the Details section of ?POSIXlt
for, um, details.
> tm <- "4/2/2004 12:45"
> strptime(tm, "%m/%d/%Y %H:%M", tz="UTC")$year
[1] 104
> strptime(tm, "%m/%d/%Y %H:%M", tz="UTC")$year + 1900
[1] 2004
Upvotes: 8