rustserderust-chrono

How to serialize and deserialize chrono::Duration?


In my current project I'm trying to store a chrono::Duration in a configuration struct, which will be serialized and deserialized occasionally using serde_json.

Unfortunately, it appears that Serialize and Deserialize aren't implemented for chrono::Duration. That said, chrono says it has support for serde via one of its optional features. I tried using this method, but now the compiler is complaining about return methods:

error[E0308]: mismatched types
 --> src/config.rs:6:10
  |
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
  |          ^^^^^^^^^ expected struct `DateTime`, found struct `chrono::Duration`
  |
  = note: expected reference `&DateTime<Utc>`
         found reference `&'__a chrono::Duration`
  = note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0308]: mismatched types
 --> src/config.rs:6:21
  |
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
  |                     ^^^^^^^^^^^ expected struct `chrono::Duration`, found struct `DateTime`
  |
  = note: expected struct `chrono::Duration`
             found struct `DateTime<Utc>`
  = note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)

Why is this happening? What can I do to fix it?

Here's the code in question:

use serde::{Serialize, Deserialize};
use chrono::{DateTime, Duration, Utc};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    pub dest_ip: String,
    #[serde(borrow)]
    pub include_paths: Vec<&'static std::path::Path>,
    pub exclude_paths: Vec<&'static std::path::Path>,
    #[serde(with = "chrono::serde::ts_seconds")]
    pub time_between_checks: Duration,
}

Also, here's the relevant bits of Cargo.toml:

serde_json = "1.0.72"
serde = { version = "1.0.130", features = ["derive"] }
chrono = { version = "0.4.19", features = ["serde"]}

Solution

  • You can use serde_with::DurationSeconds for serialization. It works identical to ts_seconds but supports more types and serialization forms.

    #[serde_with::serde_as]
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct Config {
        // ...
        #[serde_as(as = "serde_with::DurationSeconds<i64>")]
        pub time_between_checks: Duration,
    }