简体   繁体   English

在 R 中将字符串转换为日期格式

[英]Convert string into date format in R

I'm trying to convert a string into a date format "yyy-mm-dd" in R programming using below steps:我正在尝试使用以下步骤在 R 编程中将字符串转换为日期格式“yyy-mm-dd”:

date<- as.Date(S, "%Y- %m- %d")日期<- as.Date(S, "%Y- %m- %d")

where S is a vector containing a string value "15081022"其中 S 是包含字符串值“15081022”的向量

But above method is not giving an output in the format yyy-mm-dd.但上述方法没有给出格式为 yyy-mm-dd 的 output。

Can someone advise the correct command for this有人可以为此建议正确的命令吗

The as.Date() function will convert a string into date format, and the format of the output will always be in yyyy-mm-dd format in R (ISO 8601). as.Date() function 会将字符串转换为日期格式,而 output 的格式在 ZE1E1D3D40573127E0480CAF01 中将始终为yyyy-mm-dd格式(ISO)。 The format argument in the as.Date() function is to specify the date format of the string input. as.Date() function 中的format参数是指定字符串输入的日期格式。 I remember I initially thought it was specifying the output format, but it's the input format (you can change the output format with a subsequent format() function, however this will convert it back to a string).我记得我最初以为它指定了 output 格式,但它是输入格式(您可以将 output 格式更改为后续format() ZC1C425268E68385D1AB5074C17A94F14,但是这个会将其转换回字符串)。

Your string looks to be in ddmmyyyy ( %d%m%Y ) format, this should be what you specify as the format argument in as.Date() .您的字符串看起来是ddmmyyyy ( %d%m%Y ) 格式,这应该是您在as.Date()中指定为格式参数的内容。 Your format does not include hyphens, so the format argument should also not include hyphens.您的格式不包含连字符,因此format参数也不应包含连字符。 Note that ddmmyyyy , dd-mm-yyyy , dd/mm/yyyy , dd.mm.yyyy are all different date formats, even though the day, month and year are in the same order, they would be converted to date with formats %d%m%Y , %d-%m-%Y , %d/%m/%Y , and %d.%m.%Y , respectively.请注意, ddmmyyyydd-mm-yyyydd/mm/yyyydd.mm.yyyy都是不同的日期格式,即使日、月和年的顺序相同,它们也会转换为格式%d%m%Y的日期%d%m%Y%d-%m-%Y%d/%m/%Y%d.%m.%Y分别。

Further advice on working with dates and times is available in the relevant chapters of R for Data Science by Wickham & Grolemund and The R Cookbook by Teetor & Long.在 Wickham & Grolemund的数据科学R 和 Teetor & Long的 R Cookbook的相关章节中提供了有关使用日期和时间的更多建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM