#๐ Simplest way to parse string to hard UTC datetime
27 messages ยท Page 1 of 1 (latest)
@acoustic venture
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
U can use from datetime import datetime, timezone datetime.now(timezone.utc)
You can also import the const UTC
from datetime import datetime, UTC
If there's not a Z, the string is considered naive. If it ends with a Z, it's implied to be UTC
datetime.strptime("2024-07-24T07:46:32", "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)
It's usually better to use datetime.fromtimestamp(unixtime, UTC)
or even fromisoformat
>>> datetime.fromisoformat("2024-07-24T07:46:32")
datetime.datetime(2024, 7, 24, 7, 46, 32)
>>> datetime.fromisoformat("2024-07-24T07:46:32Z")
datetime.datetime(2024, 7, 24, 7, 46, 32, tzinfo=datetime.timezone.utc)
that's basically what your string is anyway
Basic example of what you want: ```py
dt = datetime.fromisoformat(ts)
if dt.tzinfo is None or dt.tzinfo.utcoffset(None) is None:
dt = dt.replace(tzinfo=UTC)
#force to utc
dt = dt.astimezone(UTC)
it's not an in-place operation. You must reassign it back
Adding Z makes it utc
.astimezone() converts it to a local naive time
What python version are you using?
works in 3.12
This works. ```py
datetime.fromisoformat("2024-07-24T07:46:32+00:00")
datetime.datetime(2024, 7, 24, 7, 46, 32, tzinfo=datetime.timezone.utc)
Looks like Z support was added in 3.11
Any version before that is considered bugged
!pip backports-datetime-fromisoformat
I guess you don't strictly need it unless you want to support the full standard
If you only consume dates produced by dt.isoformat(), you'll be fine
str(dt.tzinfo)
>>> str(datetime.fromisoformat("2024-07-24T07:46:32+00:00").tzinfo)
'UTC'
tzinfo will equal datetime.UTC
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.