4

I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version

My string is like -

2018-05-04T05:22:52.3272611-04:00

I am not able to get much info on converting the given datetime to utc.

1 Answer 1

13

That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use dateutil.parser.isoparse on it:

from dateutil.parser import isoparse
from dateutil.tz import UTC

dt = isoparse('2018-05-04T05:22:52.327261-04:00')
dt.astimezone(UTC)

Otherwise you can use dateutil.parser.parse, which is slower but allows for more unusual formats:

from dateutil.parser import parse
from dateutil.tz import UTC

dt = parse('2018-05-04T05:22:52.3272611-04:00')
dt.astimezone(UTC)

You should also use parse if you are not certain what the format will be.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.