Search code examples
rdatetimeposixct

Turning column into POSIXct date/time series


I am trying to reconfigure a column in my data frame (str = 'character') that has the format: 'MM/DD/YYYY HH:MM:SS' into a date/time series column (str = POSIXct) for use with the rmweather package.

> DNO2$`Date & Time`
    `Date & Time`
    <dttm>  
[1] "31/12/2017 24:00" 
[2] "01/01/2018 01:00"
[3] "01/01/2018 02:00" 
[4] "01/01/2018 03:00"
[5] "01/01/2018 04:00" 
[6] "01/01/2018 05:00"

In brief, I want to go from: 'MM/DD/YYYY HH:MM:SS' to: 'YYYY-MM-DD HH:MM:SS'

I've tried using the as_datetime() function in the lubridate package to do this, but I receive a strange output:

> DNO_18$`Date & Time` <- as_datetime(DNO_18$`Date & Time`, tz="Europe/London")
> head(DNO_18)
# A tibble: 6 x 8
  `Date & Time`       Rathmines Ringsend `St John`
  <dttm>              <chr>     <chr>    <chr>           
1 2031-12-20 17:24:00 0.299999… 0.90000… NoData          
2 2001-01-20 18:01:00 0.299999… 0.80000… NoData          
3 2001-01-20 18:02:00 0.299999… 0.90000… NoData          
4 2001-01-20 18:03:00 0.100000… 0.80000… NoData          
5 2001-01-20 18:04:00 0.200000… 1        NoData          
6 2001-01-20 18:05:00 0.200000… 0.90000… NoData    

Any help with this would be appreciated.


Solution

  • We can use as.POSIXct from base R

    DNO_18$`Date & Time` <- as.POSIXct(DNO_18$`Date & Time`, format = "%d/%m/%Y %H:%M")
    

    Or with lubridate

    library(lubridate)
    DNO_18$`Date & Time` <- dmy_hm(DNO_18$`Date & Time`)