1

Trying to convert time object to str, and then to datetime, but it's telling me that the utc string is not in iso (when I know it is). Code and error are below. Any advice would be appreciated.

   times = timeEntry.get()
   t = Time(times, format = 'jd', scale = 'utc')
   utc = dt.strptime(str(t.utc.iso), "iso")

ValueError: time data '2021-02-06 14:38:24.000' does not match format 'iso'

  • 1
    ISO format has a `T` between the date and time, not a space. – Barmar Nov 12 '21 at 00:03
  • I'm converting UTC directly to ISO string before trying to convert that string to a datetime object with format ISO, so shouldn't it put the T in that string? – William Mears Nov 12 '21 at 00:06
  • Agree with @Barmar, isoformat ==> `%Y-%m-%dT%H:%M:%S`, so once you have a datetime object, say, `dt`, you can use either (i) `dt.isoformat()` or (ii) `dt.strftime('%Y-%m-%dT%H:%M:%S')` – tidakdiinginkan Nov 12 '21 at 00:09
  • If you already have a datetime, why are you converting it to a string and then parsing the string? – Barmar Nov 12 '21 at 00:10
  • I want to then change the timezone info of utc with: `timez = tz.tzutc` `utc = utc.replace(tzinfo=timez)` but when I define utc with `utc=t.utc.iso` I get TypeError: replace() takes no keyword arguments – William Mears Nov 12 '21 at 00:17
  • Also getting `ValueError: time data '2021-11-11 05:00:00.0' does not match format '%Y-%m-%d %H:%M:%S %p'` – William Mears Nov 12 '21 at 00:21
  • similar to [your other question](https://stackoverflow.com/q/69937229/10197418), I voted to close this as not reproducible/caused by typo. Please have a look at the docs, section [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) - parsing directives have to match the input, they don't do magic. – FObersteiner Nov 12 '21 at 07:22
  • @MrFuppes That's reasonable for my other question, but I'm not sure if your statement applies here. Correct me if I'm wrong, but if I specify my time object to be in iso format and convert it to a string, and then strptime says that the string isn't in iso format, that's not a typo problem. – William Mears Nov 13 '21 at 06:58
  • First of all, thanks for coming back to this. There are many orphaned questions here. Then, `'iso'` is not a valid parsing directive. You might want to look up `datetime.fromisoformat` method, which efficiently parses a subset of ISO8601 formats. – FObersteiner Nov 13 '21 at 09:06
  • [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/q/127803/10197418) can give you an overview of what methods there are available. Once you have a datetime object, you can set UTC by `replace(tzinfo=...`. – FObersteiner Nov 13 '21 at 09:17
  • @MrFuppes Read through the link and looked up the method, both were incredibly helpful. Thanks so much for the advice! Will vote to close this and the other question. – William Mears Nov 14 '21 at 10:37

0 Answers0