Time differences

# It does not matter whether we have "POSIXct" or "POSIXlt" objects,
# we can always obtain differences between the tiems
t0 <- as.POSIXlt(0,origin="2020-02-01",tz="GMT")
t1 <- as.POSIXct(0,origin="2020-02-01 3:00",tz="GMT")
t2 <- as.POSIXlt(0,origin="2020-02-01 3:45",tz="GMT")
t3 <- as.POSIXct(0,origin="2020-02-01 3:45:06",tz="GMT")

# The unit of measurement for time differences is selected
# automatically. Usually it is the largest sensible unit:
t1 - t0
Time difference of 3 hours

t2 - t1
Time difference of 45 mins

t3 - t2
Time difference of 6 secs

t3 - t0
Time difference of 3.751667 hours

# The last difference is in hours and hour fractions. It might be more sensible
# to have seconds as units of measuremnt.
diff.t <- t3 - t0
units(diff.t) <- "secs"
Time difference of 13506 secs

# It is also possible to compute differences between dates:
d0 <- as.Date("2020-01-31")
d1 <- as.Date("2020-02-28")
d2 <- as.Date("2020-03-31")

# Usually the difference is in days:
d1 - d0
Time difference of 28 days

d2 - d0
Time difference of 60 days

# We may also want to see the difference in hours:
diff.d <- d1 - d0
units(diff.d) <- "hours"
Time difference of 672 hours

# It is also possible to create time durations from scratch
# From strings:
Time difference of 30 mins

# and from numbers, here it is necessary to specify the unit of measurement
as.difftime(30, units="mins")
Time difference of 30 mins

Downloadable R script and interactive version


The link with the “jupyterhub” icon directs you to an interactive Jupyter1 notebook, which runs inside a Docker container2. There are two variants of the interative notebook. One shuts down after 60 seconds and does not require a sign it. The other requires sign in using your ORCID3 credentials, yet shuts down only after 24 hours. (There is no guarantee that such a container persists that long, it may be shut down earlier for maintenance purposes.) After shutdown all data within the container will be reset, i.e. all files created by the user will be deleted.4

Above you see a rendered version of the Jupyter notebook.5


For more information about Jupyter see http://jupyter.org. The Jupyter notebooks make use of the IRKernel package.


For more information about Docker see https://docs.docker.com/. The container images were created with repo2docker, while containers are run with docker spawner.


ORCID is a free service for the authentication of researchers. It also allows to showcase publications and contributions to the academic community such as peer review.. See https://info.orcid.org/what-is-orcid/ for more information.


The Jupyter notebooks come with NO WARRANTY whatsoever. They are provided for educational and illustrative purposes only. Do not use them for production work.


The notebook is rendered with the help of the nbsphinx extension.