Search code examples
rdatetimestrftime

Why does R's strftime return the previous month for midnight?


This is right on the borderline and is a pathological case, but it is causing me trouble:

> strftime(as.POSIXct('2016-07-01', tz = 'UTC'), '%m')
[1] "06"

Seems like it should be 7, even though I know it's midnight. These are 7:

> strftime(as.POSIXct('2016-07-02', tz = 'UTC'), '%m')
[1] "07"
> strftime(as.POSIXct('2016-07-01'), '%m')
[1] "07"

What's going on here?


Solution

  • The strftime function is defaulting to your time zone, thus midnight UTC is still the previous day for all points west.

    Either add the "tz=" option to strftime function:

     strftime(as.POSIXct('2016-07-01', tz = 'UTC'), '%m', tz="UTC")
    [1] "07"  
    

    or use the format function:

    format(as.POSIXct('2016-07-01', tz = 'UTC'), '%m')
    [1] "07"