4

For a given date string such as 2009-01-01T12:00:00+0100 I want the UTC datetime object.

from datetime import datetime 
datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")

returns

datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

I cannot believe there is no method in datetime or pandas for applying the timezone-related offset to the datetime and returning plain UTC datetime.

How can I apply the tzinfo offset/delta, so that the resulting timezone is plain UTC (tzinfo=None)?

0

3 Answers 3

7

This feels a bit dirty but it does work

from datetime import datetime
orig_dt = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")  # datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
utc_time_value = orig_dt - orig_dt.utcoffset()
utc_dt = utc_time_value.replace(tzinfo=None)  # datetime.datetime(2013, 3, 21, 13, 19, 42)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution. I really hoped there is a built-in method to do this. I cannot imaging that this an uncommon intention, isn't it?
4

Here's is an actual code (built-in):

from datetime import datetime, timezone, timedelta

return datetime(yy, mm, dd, hh, min, ss, 0, timezone(timedelta(hours=5)))       # +0500
# or
return datetime(yy, mm, dd, hh, min, ss, 0, timezone(timedelta(seconds=18000))) # +0500

Comments

3

I believe .astimezone() is what you want.

from datetime import datetime, timezone
d = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z") # 2013-03-21 14:19:42+01:00
d.astimezone(timezone.utc) # 2013-03-21 13:19:42+00:00

timezone.utc is not an optional parameter in this case: The documentation says

If called without arguments (or with tz=None) the system local timezone is assumed for the target timezone.

This can lead to unintended behaviour (depending on your local timezone).

3 Comments

It depends: Documentation says "If called without arguments (or with tz=None) the system local timezone is assumed for the target timezone." Maybe you can add to your answer: from datetime import datetime, timezone\n d = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")\n d.astimezone(timezone.utc)
Sorry I edited the answer myself. :)
@MichaelDorner Yes, you are correct, thanks!

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.