简体   繁体   English

如何使用R转换日期

[英]How to transform the date using R

Currently, I have a lot of data. 目前,我有很多数据。 Associated with the data, I also have dates. 与数据相关,我也有日期。 Unfortunately, the dates are in the following format (day (Monday-Sunday), month (January-December) date (1-31) Hour:Minute:Second timezone Year). 不幸的是,日期采用以下格式(天(周一至周日),月份(一月至十二月)日期(1-31)小时:分钟:第二时区年份)。 I would like to convert this into just Month/Day(1-31)/Year. 我想将其转换成仅月/日(1-31)/年。 Following is the sample data. 以下是示例数据。

created_data
Sat Jun 20 23:45:03 +0000 2015
Sat Jun 20 23:45:06 +0000 2015
Sat Jun 20 23:45:06 +0000 2015
Sat Jun 20 23:45:08 +0000 2015
Sat Jun 20 23:45:11 +0000 2015
Sat Jun 20 23:45:13 +0000 2015
Sat Jun 20 23:45:14 +0000 2015
Sat Jun 20 23:45:15 +0000 2015

This is currently in the form of a dataframe. 当前这是数据框的形式。 The format in which I am trying to see the dataframe is the following: 我尝试查看数据框的格式如下:

Results
Jun 20 2015
Jun 20 2015
Jun 20 2015
Jun 20 2015
Jun 20 2015
Jun 20 2015
Jun 20 2015
Jun 20 2015 

Following is the code that I have tried but the result was just NA 以下是我尝试过的代码,但结果只是不适用

strptime(x = created_data, format = "%m/%d/%Y")

Result = NA

First you have to convert your character string to something that R knows how to deal with such as a POSIXct object. 首先,您必须将字符串转换为R知道如何处理的东西,例如POSIXct对象。

Given your format you can do as.POSIXct(created_data), format="%a %b %d %X %z %Y") 给定您的格式,您可以执行as.POSIXct(created_data), format="%a %b %d %X %z %Y")

Once it is in that format you can convert it back to a character string of the format you want using format such as... 一旦采用这种格式,您就可以将其转换为想要使用的格式的字符串,例如...

format(as.POSIXct(created_data, format="%a %b %d %X %z %Y"), format = "%Y/%m/%d")

The following should work, assuming the datetimes are stored in a character vector. 假设日期时间存储在字符向量中,则下面的方法应该起作用。

library("stringr")
library("dplyr")

dates <- c("Sat Jun 20 23:45:03 +0000 2015", 
           "Sat Jun 20 23:45:06 +0000 2015", 
           "Sat Jun 20 23:45:06 +0000 2015", 
           "Sat Jun 20 23:45:08 +0000 2015", 
           "Sat Jun 20 23:45:11 +0000 2015", 
           "Sat Jun 20 23:45:13 +0000 2015", 
           "Sat Jun 20 23:45:14 +0000 2015", 
           "Sat Jun 20 23:45:15 +0000 2015")

str_split_fixed(dates, pattern = " ", n=6) %>% 
  as.data.frame() %>%
  mutate(new.date = as.Date(paste(V2, V3, V6), format = "%b %d %Y"))

The basic idea being to split the string into its individual pieces using str_split_fixed() , then recombine the pieces in as.Date() 基本思想是使用str_split_fixed()将字符串拆分为单个片段,然后将其重组为as.Date()

Just a base R solution without other packages. 只是一个基本的R解决方案,而没有其他软件包。

 x <- "Sat Jun 20 23:45:03 +0000 2015"
 x1 <- format(strptime(x, "%a %b %d %H:%M:%S %z %Y", tz = "GMT"), "%b %d %Y")
 x1
[1] "Jun 20 2015"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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