1.5 Date and time
Dates are standardized in the format YYYY-MM-DD
(ISO-8601), and when contain time are of the form YYYY-MM-DD HH:MM:SS
. This procedure facilitates the programming and organization of the material, ensuring that the files named in this way are ordered chronologically in any system.
Example 1.7 The lubridate
(Grolemund and Wickham 2011) package provides a number of useful functions for dealing with temporal elements.
library(lubridate)
# Apollo 11 lands on the Moon on July 20, 1969 at 20:17 UTC (Coordinated Universal Time)
(apollo11 <- ymd_hms('1969-07-20 20:17:00'))
## [1] "1969-07-20 20:17:00 UTC"
## [1] 1969
## [1] 7
## [1] 20
## [1] 20
## [1] 17
## [1] 0
## [1] Sun
## Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat
## [1] "1969-07-20 17:17:00 -03"
## Time difference of 20461.9 days
## [1] "2024-04-22 20:17:00 UTC"
Example 1.8 In Python. ```
from datetime import datetime, timedelta
import pytz
# Apollo 11 landed on the Moon on July 20, 1969, at 8:17 PM UTC
apollo11 = datetime(1969, 7, 20, 20, 17, 0, tzinfo=pytz.utc)
# Year
print(apollo11.year)
## 1969
## 7
## 20
## 20
## 17
## 0
## Sunday
# São Paulo/Brasília time
sao_paulo_tz = pytz.timezone('America/Sao_Paulo')
apollo11_sp = apollo11.astimezone(sao_paulo_tz)
print(apollo11_sp)
## 1969-07-20 17:17:00-03:00
# Number of days since the Moon landing
now = datetime.now(pytz.utc)
days_since_landing = (now - apollo11).days
print(days_since_landing)
## 20461
# Date on which the 20,000th day of the mission will be completed
future_date = apollo11 + timedelta(days=20000)
print(future_date)
## 2024-04-22 20:17:00+00:00
References
Grolemund, Garrett, and Hadley Wickham. 2011. “Dates and Times Made Easy with lubridate.” Journal of Statistical Software 40 (3): 1–25. https://www.jstatsoft.org/v40/i03/.