Fiona
Fiona

Reputation: 477

Converting midnight in to a date time format in R

I have a very specific problem. I have been trying to convert a date time character into a date time format in R. Example: "2017-05-21 00:00:00". Whenever I try to convert it using strptime and as.POSIXct to a date time format it gives me "2017-05-21".

Thanks for any help

Upvotes: 1

Views: 1356

Answers (1)

Nathan Werth
Nathan Werth

Reputation: 5263

As @ngm says, this is only a formatting choice on the part of R. You can check to make sure it's actually midnight. Datetimes are stored as seconds past the epoch, and can actually be used in arithmetic.

t1 <- as.POSIXct("2017-05-21 00:00:00")
t1
# [1] "2017-05-21 EDT"

as.integer(t1)
# [1] 1495339200

So your time is 1,495,339,200 seconds after the epoch. Now we can look at midnight plus one second.

t2 <- as.POSIXct("2017-05-21 00:00:01")
t2
# [1] "2017-05-21 00:00:01 EDT"

as.integer(t2)
# [1] 1495339201

Which is one second higher than t1. So t1 is, in fact, midnight.

Upvotes: 4

Related Questions