Switch between dates and seconds in a well defined manner

老子叫甜甜 提交于 2019-12-12 19:38:32

问题


I run discrete event simulations where the time originates from dates. I think that simulations run much faster, when I convert all the dates to integers (relative time in seconds). What is the best way, to switch between date and seconds in a well definied way where I want to

  • set the reference time (e.g. "1970-01-01 00:00:00 GMT" or "2016-01-01 00:00:00 GMT") manually,
  • the time zone and
  • the origin (Not possible in lubridate?)

I thought I can use the origin for this purpose but it does not influence the result:

> as.numeric(as.POSIXct("2016-01-01 00:00:00 GMT",origin="2016-01-01",tz="GMT"))
> as.numeric(as.POSIXct("2016-01-01 00:00:00 GMT",origin="1970-01-01",tz="GMT"))

both result in [1] 1451606400.

(Only the tz argument changes the result, which is ok of course:
> as.numeric(as.POSIXct("2016-01-01 00:00:00 CEST", tz= "America/Chicago"))
[1] 1451628000)


回答1:


You can use difftime() to calculate the difference between some timestamp and a reference time:

as.numeric(difftime(as.POSIXct("2016-01-01 00:00:00",tz="GMT"),
    as.POSIXct("1970-01-01 00:00:00",tz="GMT"), units = "secs"))
## [1] 1451606400

By choosing another value for units, you could also get the number of minutes, hours, etc.

The reason that you get the same result for both choices of origin is that this argument is only intended to be used when converting a number into a date. Then, the number is interpreted as seconds since the origin that you pass to the function.

Internally, a POSIXct object is always stored as seconds since 1970-01-01 00:00:00, UTC, independent of the origin that you specified when doing the conversion. And accordingly, converting to numeric gives the same result for any choice of origin.

You can have a look at the documentation of as.POSIXct():

## S3 method for class 'character'
as.POSIXlt(x, tz = "", format, ...)

## S3 method for class 'numeric'
as.POSIXlt(x, tz = "", origin, ...)

As you can see, origin is only an argument for the method for numeric, but not for character.



来源:https://stackoverflow.com/questions/37881270/switch-between-dates-and-seconds-in-a-well-defined-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!