简体   繁体   中英

How can I extract year from strptime?

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.

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM