本文介绍了将许多格式的日期转换为R中的一种标准格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中做一些简单的操作,在加载表后,我遇到了一个具有多种格式的日期列。

  **日期** 
1/28/14 6:43 PM
1/29/14 4:10 PM
1/30/14 12:09 PM
1/30/14 12:12 PM
02-03-14 19:49
02-03-14 20:03
02-05-14 14:33

我需要将其转换为28-01-2014 18:43的格式,即%d-%m-%y %h:%m



我试过这个

  tablename $ Date< ; -as.Date(as.character(tablename $ Date),%d-%m-%y%h:%m)

,但是在整个column.please中填充 NA 可以帮助我获得正确的权限!

解决方案

lubridate 软件包可以快速完成以下工作:

  library(lubridate)

d< - parse_date_time(dates,names(guess_formats(dates,c(mdy HM,mdy IMp)))
d
## [1]2014-01-28 18:43:00 UTC2014年-01-29 16:10:00 UTC
## [3]2014-01-30 12:09:00 UTC2014-01-30 12:12:00 UTC
## [5]2014-02-03 19:49:00 UTC2014-02-03 20:03:00 UTC
## [7]2014-02-05 14:33: 00 UTC

#放入所需的格式

格式(d,%m-%d-%Y%H:%M:%S)
## [1]01-28-2014 18:43:0001-29-2014 16:10:0001-30-2014 12:09:00
## [4 ]01-30-2014 12:12:0002-03-2014 19:49:0002-03-2014 20:03:00
## [7]02-05 -2014 14:33:00

您需要调整 guess_formats 如果您遇到其他格式变体。


I am trying to do some simple operation in R, after loading a table i encountered a date column which has many formats combined.

    **Date**
1/28/14 6:43 PM
1/29/14 4:10 PM
1/30/14 12:09 PM
1/30/14 12:12 PM
02-03-14 19:49
02-03-14 20:03
02-05-14 14:33

i need to convert this to format like 28-01-2014 18:43 i.e. %d-%m-%y %h:%m

i tried this

 tablename$Date<-as.Date(as.character(tablename$Date),"%d-%m-%y %h:%m")

but doing this its filling NA in the entire column.please help me to get this right!

解决方案

The lubridate package makes quick work of this:

library(lubridate)

d <- parse_date_time(dates, names(guess_formats(dates, c("mdy HM", "mdy IMp"))))
d
## [1] "2014-01-28 18:43:00 UTC" "2014-01-29 16:10:00 UTC"
## [3] "2014-01-30 12:09:00 UTC" "2014-01-30 12:12:00 UTC"
## [5] "2014-02-03 19:49:00 UTC" "2014-02-03 20:03:00 UTC"
## [7] "2014-02-05 14:33:00 UTC"

# put in desired format

format(d, "%m-%d-%Y %H:%M:%S")
## [1] "01-28-2014 18:43:00" "01-29-2014 16:10:00" "01-30-2014 12:09:00"
## [4] "01-30-2014 12:12:00" "02-03-2014 19:49:00" "02-03-2014 20:03:00"
## [7] "02-05-2014 14:33:00"

You'll need to adjust the vector in guess_formats if you come across other format variations.

这篇关于将许多格式的日期转换为R中的一种标准格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:44