在包含两种日期格式的字符列中转换为日期 [英] Converting to date in a character column that contains two date formats

查看:71
本文介绍了在包含两种日期格式的字符列中转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带日期列的CSV文件,但它包含以下两种不同的日期格式

I have CSV file with "date" column but it contains two different date format as the following

7/12/2015 15:28 as m/d/yyyy hh:mm
18-04-2016 18:20  as d/m/yyyy hh:mm

如何将格式更改为m / d / yyyy hh:mm,所以我可以相互减去日期?

How can I change the format into m/d/yyyy hh: mm, So I can subtract the dates from each other?

推荐答案

如果您只有两种日期时间格式,则不需要外部软件包。只需通过解析器运行这两种格式,然后采用不丢失的一种格式即可:

External packages are not required if you simply have two datetime formats. Just run both formats through the parser and take the non-missing one:

x <- c("7/12/2015 15:28","18-04-2016 18:20")
pmax(
  as.POSIXct(x, format="%m/%d/%Y %H:%M", tz="UTC"),
  as.POSIXct(x, format="%d-%m-%Y %H:%M", tz="UTC"),
  na.rm=TRUE
)
#[1] "2015-07-12 15:28:00 UTC" "2016-04-18 18:20:00 UTC"

据我所知,绝对没有办法自动处理模棱两可的日期格式,因此硬编码可能是解决此问题的方法

As far as I know, there is absolutely no way to deal with ambiguous date formats automatically, so hard-coding is the way to go here probably.

这篇关于在包含两种日期格式的字符列中转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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