将 Postgres 时间戳转换为 Rust Chrono

问题描述

如何将 Postgresql timestamp(带时区)转换为 Rust Chrono DateTime<Utc>

示例:2020-04-12 22:10:57.0+02

解决方法

您必须使用来自 str 的自定义解析器:

let date_str = "2020-04-12 22:10:57.000+02";
// convert the string into DateTime<FixedOffset>
let datetime = DateTime::parse_from_str(&date_str,"%Y-%m-%d %H:%M:%S%.f%#z").unwrap();
// convert the string into DateTime<Utc> or other timezone
let datetime_utc = datetime.with_timezone(&Utc);

Extra info

  • %.f => .026490:类似于 .%f 但左对齐。这些都占用了前导点。
  • %#z => +09仅解析:%z 相同,但允许缺少或存在分钟。

有关详细信息,请参阅this awnser