0

I want to convert the timezones of a set list of ISO 8601 values into UTC. I won't know what the timezones of the given value in the list are (nor if they would be in a valid format, but in this case I would want to discard any values with an invalid ISO format), so by the end I want all of my values to be in UTC (ISO format).

Example ISO formatted value in my list: 2019-11-17T02:56:51+0700

I've been looking at a lot of similar things but it seems like most people want to convert the current time of the computer into some x timezone, so it's been quite confusing to me if what I want to do is possible or how exactly to do it. Would converting it into a Python datetime object be mandatory for timezone conversions, and if so, how should I go about it (e.g. pytz vs. timezone from datetime import, I'm fuzzy on the differences so any advice would be great)

martineau
  • 119,623
  • 25
  • 170
  • 301
brownleaf
  • 11
  • 5
  • Use `datetime.datetime.fromisoformat()`. Converts to a datetime, which is unavoidable. You can't convert directly between string representations of dates. – BoarGules Oct 30 '21 at 09:37
  • @BoarGules Python's `fromisoformat` requires a colon between hours and minutes in the UTC offset - you'll have to fall back to `strptime`'s `%z` here. – FObersteiner Oct 30 '21 at 09:39
  • e.g. like `datetime.strptime("2019-11-17T02:56:51+0700", "%Y-%m-%dT%H:%M:%S%z").astimezone(timezone.utc)` – FObersteiner Oct 30 '21 at 09:41
  • Thanks for the comments, so based on @BoarGules 's comment, I take it ISO format is a string and therefore I must convert it into a datetime object to be able to convert the timezone? – brownleaf Oct 30 '21 at 09:51
  • And to clarify @MrFuppes would datetime be the only thing I need to import, or should I also do ```from datetime import datetime``` for your solution? – brownleaf Oct 30 '21 at 09:51
  • To run the example from my comment, you need `from datetime import datetime, timezone`. – FObersteiner Oct 30 '21 at 09:56

0 Answers0