[英]How to Convert excel Date into Year, month and date component or NaiveDate?
I'm using rust and chrono::NaiveDate to read an Excel file with date column type in it.我正在使用 rust 和 chrono::NaiveDate 来读取其中包含日期列类型的 Excel 文件。
The date itself is formatted with "dd-mm-yyyy"日期本身的格式为“dd-mm-yyyy”
I can read the excel file and found out that the reader I use ( https://docs.rs/calamine/latest/calamine/ ) returns float value for the date我可以阅读 excel 文件,发现我使用的阅读器 ( https://docs.rs/calamine/latest/calamine/ ) 返回日期的浮点值
A documentation in Microsoft site states that the date starts from January 1st, 1900 Microsoft 站点中的文档指出该日期从 1900 年 1 月 1 日开始
The float value in it corresponds to this dates:其中的浮点值对应于这个日期:
date_value (FLOAT)![]() |
real value (in dd-mm-yyyy)![]() |
---|---|
44198 ![]() |
02-01-2021 ![]() |
44199 ![]() |
03-01-2021 ![]() |
44200 ![]() |
04-01-2021 ![]() |
etc... ![]() |
Basically I need a function or crate that can calculate month, date, and years from the float value I get.基本上我需要一个 function 或箱子,它可以根据我得到的浮点值计算月份、日期和年份。 I have no clue on how to do this.
我不知道该怎么做。
Below is my code下面是我的代码
let data_type = calamine::DataType::deserialize(deserializer);
match data_type {
Ok(DataType::Error(_)) => {
Ok(None)
}
Ok(DataType::String(date_str)) => {
let msg = "Failed to convert Date. Wrong format or empty.";
let val = NaiveDate::parse_from_str(&date_str, DATE_FORMAT)
.map_err(|_| Error::custom(msg))?;
Ok(Some(val))
}
Ok(DataType::Float(dt)) => {
println!("this is float!!!");
println!("dt: {}", dt); // dt is a float number that count the number of days from January 1st 1900
let year = ? // what should I do here ?
let month = ?
let day = ?
let val = NaiveDate::from_ymd_opt(year, month, day)
Ok(None)
}
_ => {
Ok(None)
}
}
calamine
has a dates
feature that adds a DataType.as_date()
method returning an Option<chrono::NaiveDate>
. calamine
具有dates
功能,添加了返回Option<chrono::NaiveDate>
的DataType.as_date()
方法。 There are also DataType.as_datetime()
and DataType.as_time()
.还有
DataType.as_datetime()
和DataType.as_time()
。
I don't know why it isn't documented, so use carefully.我不知道为什么它没有记录,所以小心使用。
At least, the method code could be a starting point for your own implementation.至少,方法代码可以作为您自己实现的起点。
A possible solution regarding my comment would be:关于我的评论的可能解决方案是:
use chrono::{Duration, NaiveDate};
fn main() {
let start = NaiveDate::from_ymd_opt(1900, 1, 1).expect("DATE");
let date = start.checked_add_signed(Duration::days(44198)); // date_value
println!("{}", date.unwrap());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.