Skip to content

Commit

Permalink
add a second chrono format option to convert from datetime to string
Browse files Browse the repository at this point in the history
  • Loading branch information
xcaptain committed Sep 24, 2019
1 parent b0089e2 commit a683eed
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub enum Conversion {
Timestamp,
TimestampFmt(String),
TimestampTZFmt(String),
TimestampAnyFmt(String, String),
}

impl FromStr for Conversion {
Expand All @@ -46,18 +47,18 @@ impl FromStr for Conversion {
"float" => Ok(Conversion::Float),
"bool" | "boolean" => Ok(Conversion::Boolean),
"timestamp" => Ok(Conversion::Timestamp),
_ if s.starts_with("timestamp|") => {
let fmt = &s[10..];
// DateTime<Utc> can only convert timestamps without
// time zones, and DateTime<FixedOffset> can only
// convert with tone zones, so this has to distinguish
// between the two types of formats.
_ if s.starts_with("timestamp|") && s.split('|').count() == 2 => {
let fmt: &str = s.split('|').nth(1).unwrap();
if format_has_zone(fmt) {
Ok(Conversion::TimestampTZFmt(fmt.into()))
} else {
Ok(Conversion::TimestampFmt(fmt.into()))
}
}
_ if s.starts_with("timestamp|") && s.split('|').count() == 3 => {
let fmts: Vec<&str> = s.split('|').collect();
Ok(Conversion::TimestampAnyFmt(fmts[1].into(), fmts[2].into()))
}
_ => Err(ConversionError::UnknownConversion { name: s.into() }),
}
}
Expand Down Expand Up @@ -148,6 +149,11 @@ impl Conversion {
.with_context(|| TimestampParseError { s })?,
))
}
Conversion::TimestampAnyFmt(fmt1, fmt2) => {
let s = String::from_utf8_lossy(&bytes);
let ts = DateTime::parse_from_str(&s, &fmt1).context(TimestampParseError { s })?;
ValueKind::from(ts.format(fmt2).to_string())
}
})
}
}
Expand Down Expand Up @@ -302,6 +308,14 @@ mod tests {
);
}

#[test]
fn parse_timestamp_any() {
assert_eq!(
convert("timestamp|%+|%F", "2001-02-03T04:05:06Z"),
Ok(ValueKind::from("2001-02-03"))
);
}

// These should perhaps each go into an individual test function to be
// able to determine what part failed, but that would end up really
// spamming the test logs.
Expand Down

0 comments on commit a683eed

Please sign in to comment.