Search code examples
rdatetimetimestrptimeposixlt

R help converting char to POSIXlt


I am having a lot of problems converting a char data.frame into a POSIXlt. This is my str output:

'data.frame':   5846 obs. of  5 variables:
 $ date   : Factor w/ 184 levels "1/1/2015","1/10/2015",..: 31 31 31 31 31 31 31 31 31 31 ...
 $ time   : Factor w/ 680 levels "1:00:00","1:01:00",..: 63 72 72 73 73 75 75 75 76 76 ...
 $ morning: Factor w/ 2 levels "AM","PM": 2 2 2 2 2 2 2 2 2 2 ...
 $ sender : Factor w/ 2 levels "Judith:","Saul": 2 1 1 2 2 1 2 2 1 1 ...
 $ iso    : chr  "1/8/2014 10:10:00 PM" "1/8/2014 10:19:00 PM" "1/8/2014 10:19:00 PM" "1/8/2014 10:20:00 PM" ..

I want to convert "iso" into POSIXlt using

dat$iso <- strptime(dat$iso, "%d/%m/%Y %I:%M:%S %p")

But I get NA as a result.


Solution

  • I get a similar output when doing

    > iso = "1/8/2014 10:19:00 PM"
    > strptime(iso,"%d/%m/%Y %I:%M:%S %p")
    [1] NA
    

    This is due to my default locale (fr_FR) that does not support %p. Changing this locale to "C", solves the problem:

    > Sys.setlocale(category = "LC_TIME","C")
    > strptime(iso,"%d/%m/%Y %I:%M:%S %p")
    [1] "2014-08-01 22:19:00 CEST"