简体   繁体   中英

Converting date with time in a column to week in character in R

I have data with date information including time and I'd like to convert them to a week of the year in character format. For example for the following data

Case     Time
 1   2020-01-12 11:28:46
 2   2020-01-22 10:17:24

I'd like to have a column with values such as January 6th, 2020 instead of 2020-w02 that can be produced by the date2week package. So, for this data the favourite outcome will be like:

Case     Time              time_by_day2week   favorite_time
 1   2020-01-12 11:28:46      2020-w02       January 6th, 2020
 2   2020-01-22 10:17:24      2020-w04       January 20th, 2020

So, the favorite_time column mentions the first day (Monday) of that week.

It would be much appreciated if someone can help.

Many thanks!

We can floor the Date object with floor_date and then use format

library(dplyr)
library(lubridate)
df1 %>% 
    mutate(Time = as.POSIXct(Time), 
           favorite_time =   format(floor_date(Time, "weeks",
                 week_start = 1), "%B %dth, %Y"))
#  Case                Time      favorite_time
#1    1 2020-01-12 11:28:46 January 06th, 2020
#2    2 2020-01-22 10:17:24 January 20th, 2020

data

df1 <- structure(list(Case = 1:2, Time = c("2020-01-12 11:28:46", 
"2020-01-22 10:17:24"
)), class = "data.frame", row.names = c(NA, -2L))

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