Mah
Mah

Reputation: 91

Changing the format of date with month in letters

I have Date and Time column.The main problem is that the year (2016) is not complete in the csv file and OCT is not numeric.

Date        Time         rtime
20-Oct-16 14:02:00       20-Oct-16 14:02:00
20-Oct-16 14:02:03       20-Oct-16 14:02:03

I want another column called newtime with this format

newtime
2016-10-20 14:02:00
2016-10-20 14:02:03 

Any suggestions on how to make the month in a regular number format and making 16 into 2016.

Upvotes: 1

Views: 2092

Answers (3)

akrun
akrun

Reputation: 886938

We can also use as.POSIXct with format

as.POSIXct("20-Oct-16 14:02:00", format = "%d-%b-%y %H:%M:%S")
#[1] "2016-10-20 14:02:00 IST"

Upvotes: 1

Edgar Santos
Edgar Santos

Reputation: 3514

With lubridate you don't need to specify if the month comes with name (Oct) or as a decimal number (10) or the year is 2016 or 16. Lubridate functions parse heterogeneous date-times formats. For instance:

library(lubridate)
df$newtime = dmy_hms(df$rtime) 

       Date     Time              rtime             newtime
1 20-Oct-16 14:02:00 20-Oct-16 14:02:00 2016-10-20 14:02:00
2 20-Oct-16 14:02:03 20-Oct-16 14:02:03 2016-10-20 14:02:03

If you use strptime then you need to define the format. See ?strptime.

Upvotes: 3

www
www

Reputation: 39154

We can use strptime

strptime("20-Oct-16 14:02:00", "%d-%b-%y %H:%M:%S")

Or dmy_hms from lubridate

lubridate::dmy_hms("20-Oct-16 14:02:00")

Upvotes: 2

Related Questions