Drops time when subtracting from POSIXlt object

99 views Asked by At

I am trying to subtract an hour (3600 s) from this time object that is defined as 01:00. When I do so, the time component disappears, and I am left with the date only. I need to preserve the time component--how do I do so? This only happens when the result of my subtraction is 00-00.

test <- strptime("2016-09-02_01-00", format =  "%Y-%m-%d_%H-%M", tz = "UTC")
test
[1] "2016-09-02 01:00:00 UTC"
test-3600
[1] "2016-09-02 UTC"
1

There are 1 answers

1
Ben Bolker On BEST ANSWER

This is a difference between content and representation.

fmt <- "%Y-%m-%d_%H-%M"
test <- strptime("2016-09-02_01-00", 
     format = fmt, tz = "UTC")
str(test)
## POSIXlt[1:1], format: "2016-09-02 01:00:00"

Subtracting 3600 does change the structure (from POSIXlt to POSIXct) ...

str(test-3600)
## POSIXct[1:1], format: "2016-09-02"

... but the change in formatting is just due to R trying to be helpful and printing the simplest representation available. The time information hasn't actually gone away. From ?strptime (thanks @DavidArenburg):

The default for the format methods is "%Y-%m-%d %H:%M:%S" if any element has a time component which is not midnight, and "%Y-%m-%d" otherwise

As @MrFlick states in comments, you can override this by specifying a format string ...

fmt2 <- "%Y-%m-%d %H:%M:%S"
format(test-3600,fmt2)
## [1] "2016-09-02 00:00:00"