How to use Utc.date_from_str()

I can't figure this out from the docs or find an example. Here's my first try:

use chrono::{Utc, TimeZone};

fn main()
{
    
   match Utc.datetime_from_str("2020-03-18T23:08:36.8098960+05:30", "%+") {
       Ok(time) => {
           println!("bingo: {}", time);
       }
       Err(e) => {
           println!("woops: {}", e);
       }
   };
}

playground

Then I tried this:

chrono::{Utc, DateTime, Local, TimeZone};

fn main()
{
    
   match Local.datetime_from_str("2020-03-18T23:08:36.8098960+05:30", "%+") {
       Ok(time) => {
           let then_utc: DateTime<Utc> = time.with_timezone(&Utc);
           println!("bingo: {}", then_utc);
       }
       Err(e) => {
           println!("woops: {}", e);
       }
   };
}

playground

Update: From responses to 28 September this looks like a bug so I created issue #489.

I don't know why this isn't working, but I could get it to work if I leave off the timezone:

Local.datetime_from_str("2020-03-18T23:08:36.8098960", "%Y-%m-%dT%H:%M:%S%.f")

playground

1 Like

Thanks, maybe this is a bug. Seems unlikely but I'll open an issue unless someone can offer an explanation.

In the mean time I can use your workaround as the TimeZone isn't important in my use case, so thanks very much for looking into it.

1 Like

I just wish I could've solved it for you! I tried both in the playground and on my local machine, so it's pretty odd... I'll also be curious what the explanation is.

1 Like

From responses to 28 September this looks like a bug so I created issue #489.

1 Like

I commented in the linked issue with the resolution, but there's also an open question about what the right way to handle this is, if folks feel like commenting.

1 Like