如何将MM/DD/YYYY HH:MM格式的分钟级日期转换为MM/DD/YYYY格式
Hey there! Let's break down the most efficient ways to strip the hour-minute part from your date-time strings. Since you're working in R (based on your head(data$time) snippet), here are practical, easy-to-use approaches tailored to different needs:
1. Pure String Manipulation (Fastest, No Extra Packages)
If you just need the date as a string and don't plan to do date-related operations later, this is your best bet—no type conversion overhead, just straight-up string editing.
Using Base R's sub()
The sub() function lets you match and replace a pattern. Here, we target everything after the first space (which is the HH:MM part) and replace it with nothing:
time_vec <- c("11/10/2019 12:20", "10/10/2019 13:10", "03/01/2020 13:12", "11/10/2018 17:46") date_strings <- sub("\\s.*$", "", time_vec) # Result: "11/10/2019" "10/10/2019" "03/01/2020" "11/10/2018"
\\smatches the space between date and time.*$matches any character until the end of the string
Using stringr (More Readable)
If you're already using the tidyverse, str_remove() makes the intent even clearer:
library(stringr) date_strings <- str_remove(time_vec, "\\s.*")
Same result, just cleaner syntax.
2. Convert to Date Type (Robust for Future Operations)
If you need to sort, filter, or calculate with these dates later, converting them to R's Date class is smarter. It's slightly slower than pure string ops, but avoids messy string handling down the line.
Base R as.Date()
Specify the input format to parse the string correctly:
date_dates <- as.Date(time_vec, format = "%d/%m/%Y") # If you need it back as a string: date_strings <- format(date_dates, "%d/%m/%Y")
%d= day,%m= month,%Y= 4-digit year (matches your date format)
lubridate (No Format Strings Needed)
The lubridate package auto-detects date formats, so you don't have to remember %d/%m/%Y:
library(lubridate) date_dates <- dmy_hm(time_vec) %>% as.Date() # Convert back to string if needed: as.character(date_dates)
dmy_hm()parses strings in day-month-year-hour-minute orderas.Date()drops the time component
Which is Most Efficient?
- Pure string methods (
sub()/str_remove()): Fastest, since they skip type conversion. Ideal if you only need the date as a string. - Date type conversion: Better for long-term workflows where you'll manipulate dates (sorting, filtering, arithmetic). The small performance hit is worth the robustness.
内容的提问来源于stack exchange,提问作者Kash

