You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中拆分时间戳?以芝加哥出租车数据集为例

嘿,我来帮你搞定这个日期拆分的问题!之前用POSIXct没成功大概率是没有匹配对时间戳的格式,我给你几种靠谱的实现方法,选你顺手的来:

方法一:用lubridate包(最推荐)

lubridate是R里处理日期时间的“瑞士军刀”,语法简洁还不用纠结格式参数(它会自动识别大部分常见格式):

  1. 先安装并加载包:
install.packages("lubridate")
library(lubridate)
  1. 把Trip.Start.Timestamp转换成标准的日期时间对象:
    如果你的时间戳是类似"2023-10-05 14:30:00"的年-月-日格式,用ymd_hms();如果是"10/05/2023 2:30 PM"的月/日/年带AM/PM的格式,就用mdy_hms():
# 根据你的实际格式二选一
chicagotaxidata$Trip.Start.Timestamp <- ymd_hms(chicagotaxidata$Trip.Start.Timestamp)
# chicagotaxidata$Trip.Start.Timestamp <- mdy_hms(chicagotaxidata$Trip.Start.Timestamp)
  1. 拆分出日期和时间列:
# StartDate是Date类型,只保留年月日
chicagotaxidata$StartDate <- as.Date(chicagotaxidata$Trip.Start.Timestamp)
# StartTime是字符型,保留时分秒
chicagotaxidata$StartTime <- format(chicagotaxidata$Trip.Start.Timestamp, "%H:%M:%S")

方法二:Base R原生实现(不用额外装包)

如果你不想依赖第三方包,用Base R也能搞定,核心是要指定正确的format参数,这也是很多人用POSIXct失败的关键:

  1. 转换为POSIXct对象:
    比如你的时间戳格式是"YYYY-MM-DD HH:MM:SS",就这么写:
chicagotaxidata$Trip.Start.Timestamp <- as.POSIXct(
  chicagotaxidata$Trip.Start.Timestamp,
  format = "%Y-%m-%d %H:%M:%S"
)

如果是"MM/DD/YYYY hh:mm:ss AM/PM"格式,format要改成"%m/%d/%Y %I:%M:%S %p"(%I是12小时制,%p识别AM/PM)。

  1. 提取日期和时间:
chicagotaxidata$StartDate <- as.Date(chicagotaxidata$Trip.Start.Timestamp)
chicagotaxidata$StartTime <- format(chicagotaxidata$Trip.Start.Timestamp, "%H:%M:%S")

方法三:tidyverse管道风格(适合数据清洗流程)

如果你平时用dplyr做数据处理,用管道操作会更流畅:

library(tidyverse)
library(lubridate)

chicagotaxidata <- chicagotaxidata %>%
  mutate(
    # 先转换为日期时间对象
    Trip.Start.Timestamp = ymd_hms(Trip.Start.Timestamp),
    # 拆分出日期和时间
    StartDate = as.Date(Trip.Start.Timestamp),
    StartTime = format(Trip.Start.Timestamp, "%H:%M:%S")
  )

最后提醒一下:如果转换时还是报错,先打印几条Trip.Start.Timestamp的内容,确认它的具体格式,再对应调整转换函数(lubridate的ymd_hms/mdy_hms等)或者format参数就好啦!

内容的提问来源于stack exchange,提问作者Vera Setiawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:27:44