Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Postgres timestamp to Rust Chrono

How to covert a PostgreSQL timestamp (with time zone) to Rust Chrono DateTime<Utc>?

Example: 2020-04-12 22:10:57.0+02

like image 995
Ralph Bisschops Avatar asked Sep 07 '25 22:09

Ralph Bisschops


2 Answers

You have to use the custom parser from 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: Similar to .%f but left-aligned. These all consume the leading dot.
  • %#z => +09: Parsing only: Same as %z but allows minutes to be missing or present.

For more info, see this awnser.

like image 137
Ralph Bisschops Avatar answered Sep 09 '25 16:09

Ralph Bisschops


The Postgres type TIMESTAMP is only convertible to chrono's NaiveDateTime.

In order to convert to chrono's DateTime<Utc>, you must use the Postgres type TIMESTAMP WITH TIME ZONE for your column.

like image 26
randbw Avatar answered Sep 09 '25 15:09

randbw