在 R 中格式化日期

R 中的时间序列数据处理

Harrison Brown

Graduate Researcher in Geography

时间元素的顺序

日、月、年的顺序:

  • 美国:12/20/2022
  • 英国:20/12/2022
  • 大部分时间会有歧义:
    • 6/4/2010:6 月 4 日还是 4 月 6 日?

 

"时间元素":

  • 日、月、年
  • 时、分、秒

R 中的时间序列数据处理

ISO 8601

  • 时间元素按从大到小排列
    • 年 -> 月 -> 日 -> …
    • 2022-06-04
    • 2022-06-04 = 2022 年 6 月 4 日
  • 时间元素由特定字符分隔
    • 日期元素之间用连字符(-
    • 2022-06-04
  • 提高可读性与清晰度
    • 2022-06-04 vs. 20220604
R 中的时间序列数据处理

格式化日期和时间

lubridate::parse_date_time()

earthday <- "April 22, 2022"

parse_date_time(earthday,
                orders = "%B %d, %Y")
[1] "2022-08-22 UTC"

?strptime 查看转换说明

常用转换说明:

时间元素 转换说明
年(YYYY %Y
年(yy %y
日(dd %d
月(mm %m
月(August) %B
月(Aug) %b
R 中的时间序列数据处理

解析多种日期格式

dates_vector <- c("12/20/2022",
                  "2022-12-21",
                  "December 22, 2022")
dates_vector
[1] "12/20/2022"
[2] "2022-12-21"
[3] "December 22, 2022"
library(lubridate)
parse_date_time(
  dates_vector,
  orders = c("%m/%d/%Y",
             "%Y-%m-%d",
             "%B %d, %Y"))
[1] "2022-12-20 UTC"
[2] "2022-12-21 UTC"
[3] "2022-12-22 UTC"
R 中的时间序列数据处理

Let's practice

R 中的时间序列数据处理

Preparing Video For Download...