1

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"
SilvanD
  • 325
  • 2
  • 14
  • 2
    The time component is still there, it just doesn't print with all dates in a vector have time midnight. If you want to enforce a format to display, use `strftime()` or `format()` or something. – MrFlick Dec 19 '16 at 16:44
  • 1
    That's also documented under `?strptime` "*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*" – David Arenburg Dec 19 '16 at 16:46

1 Answers1

3

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"
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453