Divi
Divi

Reputation: 1634

Strptime not able to convert date and time

My attempt to format date like this results in NA NA. Neither the date nor the time is getting converted. What am I doing wrong?

    x <- strptime(c("2013-12-12", "08:43:24.967"),"%Y-%m-%d %H:%M:%OS")

Upvotes: 0

Views: 597

Answers (2)

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

With the format string that you have supplied, strptime expects a vector of date-time strings. You have a vector containing date and time as separate vector elements. This is incorrect.

Instead of passing c("2013-12-12", "08:43:24.967") (two elements, date then time), you need to pass "2013-12-12 08:43:24.967" (one element, date-time).

The data you have can be put in the proper format with paste:

strptime(paste("2013-12-12", "08:43:24.967"),format="%Y-%m-%d %H:%M:%OS")
[1] "2013-12-12 08:43:24"

The fractional seconds aren't printed above, because the default is to not print them. But the expression does capture them (with the default options(digits.secs=NULL)). They would be printed with the proper format string for output, or a specification of the number of digits to print (e.g. options(digits.secs=3))

Upvotes: 3

vijay
vijay

Reputation: 494

You need to pass a date string as first argument to strptime function follwed by the date format. It seems like you entered 0 in the date format string and please remove that milliseconds part in the date string.

You can use statement like this:

strptime("2013-12-12 08:43:24", "%Y-%m-%d %H:%M:%S")

Upvotes: 0

Related Questions