0

Hi Have 2 columns in a dataframe. Column 1 has Dates like 2017-01-01 and column 2 has time stamp like 1:00 PM.

I need to create another column that combines these 2 information and gives me the 2017-01-01 13:00:00

nityansh seth
  • 31
  • 2
  • 9
  • 3
    `lubridate::ymd_hm(paste("2017-01-01", "1:00 PM"))` – d.b Sep 05 '17 at 22:04
  • Related - https://stackoverflow.com/questions/14359546/converting-two-columns-of-date-and-time-data-to-one and https://stackoverflow.com/questions/32784786/how-to-merge-date-and-time-into-one-datetime-column and https://stackoverflow.com/questions/24105984/combining-date-and-time-into-a-date-column-for-plotting and https://stackoverflow.com/questions/11609252/r-tick-data-merging-date-and-time-into-a-single-object and .... – thelatemail Sep 05 '17 at 22:15
  • Yeah sorry i missed that. i used as.POSIXct(paste(x$date, format(as.POSIXct(x$time,format='%I:%M %p'),"%H:%M")), format="%Y-%m-%d %H:%M") – nityansh seth Sep 05 '17 at 22:48
  • 1
    There's no need to convert your date and time column to `POSIXct` before you paste. By pasting you are converting them back to `character` format, only to change it back to `Date` format, very redundant. – D.sen Sep 05 '17 at 23:11

2 Answers2

5

Use as.POSIXct to convert from character to date format.

df$date.time <- as.POSIXct(paste(df$date, df$time), format = "%Y-%m-%d %I:%M %p")

EDIT:

To provide some further context... You paste the date and the time column together to get the string 2017-001-01 1:00 PM.

You then input the format of the string as a POSIXct argument using format =. You can see the relationship between symbols and their meaning here.

D.sen
  • 938
  • 5
  • 14
4

Reproducible example

library(lubridate)
A <- data.frame(X1 = ymd("2017-01-01"),
                X2 = "1:00 PM", stringsAsFactors=F)

#         X1      X2
# 1 2017-01-01 1:00 PM

solution

library(dplyr)
library(lubridate)
temp <- A %>% 
          mutate(X3 = ymd_hm(paste(X1, X2)))

output

          X1      X2                  X3
      <date>   <chr>              <dttm>
1 2017-01-01 1:00 PM 2017-01-01 13:00:00

multi-row input

B <- data.frame(X1 = ymd("2017-01-01", "2016-01-01"),
                X2 = c("1:00 PM", "2:00 AM"), stringsAsFactors=F)

temp <- B %>% 
          mutate(X3 = ymd_hm(paste(X1, X2)))


#           X1      X2                  X3
#       <date>   <chr>              <dttm>
# 1 2017-01-01 1:00 PM 2017-01-01 13:00:00
# 2 2016-01-01 2:00 AM 2016-01-01 02:00:00
CPak
  • 13,260
  • 3
  • 30
  • 48