Amer
Amer

Reputation: 2251

POSIX formatted Date and Time

I am reading this from csv file into R

df <-

ID   DATE         TIME
1    10/14/2000    8:30:05
2    02/13/2001    12:05:05

I have trouble converting this to POSIX formatted date and time.

df <-
ID   DATE         TIME        DATETIMEPOSIX
1    10/14/2000    8:30:05    2000-10-14 8:30:05
2    02/13/2001    01:05:05   2001-02-13 13:05:05   

I have tried this but got NAs

df$DateTime <- paste(df$DATE, df$TIME)
df$DateTimePOSIX <- strptime(df$DateTime,  format = "%Y-%m-%d %H:%M:%S")

Upvotes: 0

Views: 8000

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26248

The format argument needs to be the format of what it's reading, not what you want the output to be.

Also, I assume your date component is in the American version of 'mm/dd/yyyy'

Consider

DateTime <- "10/14/2000 8:30:05"

as.POSIXct(DateTime, format = "%m/%d/%Y %H:%M:%S")
"2000-10-14 08:30:05 AEDT"

So you'll want

df$DateTimePOSIX <- as.POSIXct(df$DateTime,  format = "%m/%d/%Y %H:%M:%S")

df
#   ID       DATE     TIME            DateTime       DateTimePOSIX
# 1  1 10/14/2000  8:30:05  10/14/2000 8:30:05 2000-10-14 08:30:05
# 2  2 02/13/2001 12:05:05 02/13/2001 12:05:05 2001-02-13 12:05:05

Upvotes: 2

Related Questions