R Extract day from datetime
Asked Answered
K

7

13

Hi I need to remain only with the day of each date:

df<-data.frame(x=c("2014-07-24 00:00:00", 
"2014-07-24 00:00:00", "2014-07-11", "2014-07-11" ,"2014-07-16" ,"2014-07-14"))
as.Date(df$x,format="%Y-%m-%d" )

I tried this:

df$dia<-as.Date(df$x, format="%d")

But I get a full date and different from the orginal.

I don't want to install another package to do this. How can I solve it? Thanks

Koziol answered 25/9, 2014 at 16:29 Comment(2)
df$x <- as.Date(df$x) ? Do you want the name of the day? weekdays(df$x) Do you want a numeric result? Your question is not clear.Tryck
A date, by definition, is a year, month, and day. You need to provide more information for people to best help you. Some of the values of df$x have times. What timezone are they in? Are the times always "00:00:00"? If you just want the day as a string, you can use format(as.Date(df$x,format="%Y-%m-%d"), "%d").Martguerita
S
31

Are you looking for format?

format(as.Date(df$x,format="%Y-%m-%d"), format = "%d")
# [1] "24" "24" "11" "11" "16" "14"
Sorb answered 25/9, 2014 at 16:46 Comment(0)
B
4

If your dates are always in the same position and format, you have another option with substr(). The call below starts with the 9th position -- the start of the day -- and ends with the 10th -- the second number of the day.

substr(x = df$x, start = 9, stop = 10)
[1] "24" "24" "11" "11" "16" "14"
Bogosian answered 25/9, 2014 at 21:34 Comment(1)
If somebody is looking for numeric or factor format with the same functionality, then simply use the type converter: as.numeric or as.factor.Actomyosin
T
2

Since your result will no longer be a date anyway, you could use gsub

gsub("(.*)[-]", "", df$x)
# [1] "24" "24" "11" "11" "16" "14"
Tryck answered 25/9, 2014 at 16:54 Comment(0)
S
1

Try:

sapply(strsplit(as.character(df$x), '-'), function(x) x[3])
[1] "24" "24" "11" "11" "16" "14"
Scissor answered 25/9, 2014 at 16:52 Comment(0)
M
1

If you have already set the class of the variable to date type then try

df$dia <- format(df$x, "%d")

else, nest the format function within as.date function

Matthaus answered 1/9, 2018 at 0:55 Comment(0)
S
0

It's a function in lubridate

library(lubridate)
day(date)
Satirist answered 24/11, 2023 at 2:22 Comment(0)
T
-1

You can simply use weekdays(df$date) to extract the day of the week from the date. Only make sure the column is of type Date or convert using as.Date().

Tantamount answered 13/9, 2016 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.