简体   繁体   中英

trying to extract date from timestamp R

I have a df with columns

id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
time = c("2020-12-31 16:00:00 PST", "2020-12-31 16:00:00 PST", "2020-12-31 16:00:00 PST", "2020-12-31 16:00:01 PST", "2020-12-31 16:00:01 PST", "2020-12-31 16:00:02 PST", "2020-12-31 16:00:03 PST", "2020-12-31 16:00:03 PST", "2020-12-31 16:00:03 PST", "2020-12-31 16:00:03 PST")

df = data.frame(id, time)

I extracted the time by using the anytime() function on my original column of timestamps so these values are doubles. I would like to keep just the date in the column and removing the time and timezone. So for example the first value in the times column would be "2020-12-31". Is there a fast way to do this?

Originally I was doing:

df$'date' = as.character(anytime(df$time)) 

df = df %>% 
  mutate(date = str_split_fixed(df$date, " ", 2)) %>%
  mutate(date = as.Date(date))

However, it takes a while to cast each value to a string and then split based on the space and then cast the dates back into date format (which is also causing a problem with the dimensions as the data column is only showing the dates but casting that column into as.Date() is showing an issue. Is there an quicker way to do this? Thanks!

as.Date will take a string even if it includes the time. There is no need to remove that prior to making it a date.

as.Date("2020-12-31 16:00:00 PST")
# [1] "2020-12-31"

Using your code and data

df = df %>% 
  mutate(date = as.Date(time))

#    id                    time       date
# 1   1 2020-12-31 16:00:00 PST 2020-12-31
# 2   2 2020-12-31 16:00:00 PST 2020-12-31
# 3   3 2020-12-31 16:00:00 PST 2020-12-31
# 4   4 2020-12-31 16:00:01 PST 2020-12-31
# 5   5 2020-12-31 16:00:01 PST 2020-12-31
# 6   6 2020-12-31 16:00:02 PST 2020-12-31
# 7   7 2020-12-31 16:00:03 PST 2020-12-31
# 8   8 2020-12-31 16:00:03 PST 2020-12-31
# 9   9 2020-12-31 16:00:03 PST 2020-12-31
# 10 10 2020-12-31 16:00:03 PST 2020-12-31

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