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"
year(apollo11)    # year
## [1] 1969
month(apollo11)   # month
## [1] 7
day(apollo11)     # day
## [1] 20
hour(apollo11)    # hour
## [1] 20
minute(apollo11)  # minute
## [1] 17
second(apollo11)  # second
## [1] 0
wday(apollo11, label = TRUE)  # week day
## [1] Sun
## Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat
with_tz(apollo11, 'America/Sao_Paulo') # São Paulo/Brasília time
## [1] "1969-07-20 17:17:00 -03"
now()-apollo11 # number of days from apollo11 landing to the closing of this material
## Time difference of 20461.9 days
apollo11+(20000*24*3600) # date on which 20 thousand days of the mission are completed
## [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
# Month
print(apollo11.month)
## 7
# Day
print(apollo11.day)
## 20
# Hour
print(apollo11.hour)
## 20
# Minute
print(apollo11.minute)
## 17
# Second
print(apollo11.second)
## 0
# Day of the week
print(apollo11.strftime('%A'))
## 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/.