Skip to content

Deserializing DateTime from unix timestamp is not implemented, despite description #1484

@jmaximusix

Description

@jmaximusix

The Deserialize Trait can't deserialize DateTimes from timestamps despite the error message you get. I tried tracking it down in the source code, I hope the cited references are correct.

The Deserialize Trait only calls the deserialize_str() function

impl<'de> de::Deserialize<'de> for DateTime<FixedOffset> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
deserializer.deserialize_str(DateTimeVisitor)
}
}

where, in spite of the expecting() stating it accepts "a formatted date and time string or a unix timestamp" it only calls the parse() function

impl<'de> de::Visitor<'de> for DateTimeVisitor {
type Value = DateTime<FixedOffset>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a formatted date and time string or a unix timestamp")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
value.parse().map_err(E::custom)
}
}

which in turn is implemented to only try and deserialize rfc3339 strings

chrono/src/format/parse.rs

Lines 523 to 534 in f4adc28

impl str::FromStr for DateTime<FixedOffset> {
type Err = ParseError;
fn from_str(s: &str) -> ParseResult<DateTime<FixedOffset>> {
let mut parsed = Parsed::new();
let (s, _) = parse_rfc3339_relaxed(&mut parsed, s)?;
if !s.trim_start().is_empty() {
return Err(TOO_LONG);
}
parsed.to_datetime()
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions