過了多久?
若要更細緻地控制兩個日期時間的差異,可以使用 base 的 difftime() 函式。例如,不用 time1 - time2,而是改用 difftime(time1, time2)。
difftime() 接受 units 引數,用來指定差值的單位。可用的選項有 "secs"、"mins"、"hours"、"days" 或 "weeks"。
來練習一下,找出自從第一位人類踏上月球以來經過了多久。你也會看到 lubridate 的 today() 與 now() 函式,當不帶引數呼叫時,會回傳你系統時區的目前日期與時間。
本練習屬於課程
在 R 中處理日期與時間
練習說明
- 阿波羅 11 號於 1969 年 7 月 20 日登陸。使用
difftime()計算today()與date_landing之間相差的天數。 - Neil Armstrong 於 02:56:15 UTC 踏上月面。使用
difftime()計算now()與moment_step之間相差的秒數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# The date of landing and moment of step
date_landing <- mdy("July 20, 1969")
moment_step <- mdy_hms("July 20, 1969, 02:56:15", tz = "UTC")
# How many days since the first man on the moon?
difftime(___, ___, units = ___)
# How many seconds since the first man on the moon?
___