将多种日期时间格式转换为一种标准格式 [英] Convert many formats of date-time to one standard format

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

问题描述

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

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

我需要将此格式转换为2014年1月28日18:43的格式,即%d -%m-%y%h:%m

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

我尝试了此

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

,但这样做会在整个列中填充 NA

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

推荐答案

lubridate 软件包可以使我正确!

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"

您需要使用 guess_formats调整矢量,如果您遇到其他格式的变体。

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆