如何更改日期列的格式并使其保留为日期列

问题描述 投票:0回答:1

我希望这个问题不会重复,但我真的找不到答案。 我有一个日期类列,格式为 yyyy-mm-dd。我需要将此列导出为 dd-mm-yyyy 列中的 Excel,但仍作为日期类列。

我尝试过的每个选项都会在设法更改格式后将日期类列转换为字符类。

这是一些示例数据:

structure(c(18793, 18802, 18802, 18795, 18810, 18789, 18802, 
18807, 18802, 18817, 18788, 18790, 18796, 18810, 18779, 18800, 
18783, 18791, 18808, 18806, 18802, 18808, 18800, 18801, 18860, 
18812, 18812, 18812, 18808, 18793, 18810, 18789, 18792, 18800, 
18789, 18805, 18800, 18792, 18816, 18807, 18804, 18787, 18795, 
18793, 18815, 18795, 18833, 18798, 18807, 18805), class = "Date")

希望你能帮忙!

r date character
1个回答
0
投票

试试这个:

format(df, "%d-%m-%Y")

df = tibble(
  as_date = df, 
  as_char = format(df, "%d-%m-%Y"))

> df
# A tibble: 50 × 2
   as_date    as_char   
   <date>     <chr>     
 1 2021-06-15 15-06-2021
 2 2021-06-24 24-06-2021
 3 2021-06-24 24-06-2021
 4 2021-06-17 17-06-2021
 5 2021-07-02 02-07-2021
 6 2021-06-11 11-06-2021
 7 2021-06-24 24-06-2021
 8 2021-06-29 29-06-2021
 9 2021-06-24 24-06-2021
10 2021-07-09 09-07-2021

#
write_xlsx(df, "temp.xlsx")

MS Excel 输出:

# Toy data
df <- structure(
  c(18793, 18802, 18802, 18795, 18810, 18789, 18802, 18807, 18802, 18817, 
    18788, 18790, 18796, 18810, 18779, 18800, 18783, 18791, 18808, 18806, 
    18802, 18808, 18800, 18801, 18860, 18812, 18812, 18812, 18808, 18793, 
    18810, 18789, 18792, 18800, 18789, 18805, 18800, 18792, 18816, 18807, 
    18804, 18787, 18795, 18793, 18815, 18795, 18833, 18798, 18807, 18805), 
  
  class = "Date")
© www.soinside.com 2019 - 2024. All rights reserved.