如何在R中将dd / mm / yyyy hh:mm:ss转换为dd-mm-yy hh:mm? [英] How do I convert dd/mm/yyyy hh:mm:ss to dd-mm-yy hh:mm in R?

查看:179
本文介绍了如何在R中将dd / mm / yyyy hh:mm:ss转换为dd-mm-yy hh:mm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有时间戳的数据帧作为字符类型,格式为 dd-mm-yyyy hh:mm

例如:

I have dataframe with timestamp as character type in the format dd-mm-yyyy hh:mm,
for example:

"05-02-2018 06:30"

我需要以 mm-dd-yyyy hh:mm 的格式输出,即:

I need output in the format of mm-dd-yyyy hh:mm, i.e.:

"02-05-2018 06.30"

我尝试使用函数mdy()和as.POSIXct

的lubridate库,但是它不适用于所有记录-

很少抛出警告消息无法解析。

,它主要用于 day为> 12 的日期,例如:

I tried lubridate library with function mdy() and also as.POSIXct
but its not working for all of the records -
for few its throwing warning message "failed to parse." and
it is mostly for dates where day is > 12, for example:

"19-06-2017 16:30"
"22-10-2017 11:45"
"14-09-2017 16:00"


推荐答案

使用?strptime()显示帮助。帮助文件中有一个格式属性列表,使用 strptime()时必须指定:

Use ?strptime() to display help. In the help file there is a list of format properties which you have to specify when using strptime():

strptime()帮助

对您的问题最重要的是:

The most important for your problem are:

%d
以十进制数表示的月份中的某天( 01–31)。

%d Day of the month as decimal number (01–31).

%H
以十进制数表示的小时数(00-23)。由于ISO 8601允许使用这些特殊的例外字符串,例如24:00:00,因此可以输入。

%H Hours as decimal number (00–23). As a special exception strings such as 24:00:00 are accepted for input, since ISO 8601 allows these.

%m
以十进制数表示的月份(01 –12)。

%m Month as decimal number (01–12).

%M
以十进制数字表示(00-59)。

%M Minute as decimal number (00–59).

%Y
有世纪的年份。请注意,虽然原始格里高利历中没有零,但ISO 8601:2004定义它是有效的(解释为1BC):请参见 https://en.wikipedia.org/wiki/0_(年份)。请注意,该标准还规定,日历中1582年之前的年份只能在相关各方同意的情况下使用。

%Y Year with century. Note that whereas there was no zero in the original Gregorian calendar, ISO 8601:2004 defines it to be valid (interpreted as 1BC): see https://en.wikipedia.org/wiki/0_(year). Note that the standards also say that years before 1582 in its calendar should only be used with agreement of the parties involved.

字符串的一部分也是分隔符。在您的情况下为-。

Part of the string is a Seperator as well. In your case "-".

然后,您可以使用strptime()和format()交换月份和日期。使用您的示例:

Then you can exchange the month and day using strptime() and format(). Using your example:

dates <- c( "19-06-2017 16:30" ,"22-10-2017 11:45", "14-09-2017 16:00")
dates <- strptime(dates, format="%d-%m-%Y %H:%M")
dates_changed <- format(dates, "%m-%d-%Y %H:%M")

这篇关于如何在R中将dd / mm / yyyy hh:mm:ss转换为dd-mm-yy hh:mm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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