3

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

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

Ralph Bisschops
  • 1,888
  • 1
  • 22
  • 34
  • Does this answer your question? [How can I read a timestamp with timezone (timestamptz) value from PostgreSQL in Rust?](https://stackoverflow.com/questions/59760741/how-can-i-read-a-timestamp-with-timezone-timestamptz-value-from-postgresql-in) – Bergi May 31 '21 at 13:42

2 Answers2

1

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.

Ralph Bisschops
  • 1,888
  • 1
  • 22
  • 34
1

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.

randbw
  • 490
  • 5
  • 13