Reputation: 544
On Python 3.9.6, this works as expected:
import datetime
A = datetime.datetime(2021,1,1)
A.astimezone(datetime.timezone.utc)
>> datetime.datetime(2021, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
But on Python 3.9.5, I get:
import datetime
A = datetime.datetime(2021,1,1)
A.astimezone(datetime.timezone.utc)
>> datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)
Why this behaviour? I just want to add a utc aware tzone to the naive datetime by preserving the raw datetime data, as in 3.9.6.
Upvotes: 1
Views: 5964
Reputation: 25594
I've tested on Windows, with mentioned Python versions. The time zone setting of my machine is 'Europe/Berlin', so the naive datetime datetime(2021,1,1)
is one hour ahead of UTC. Therefore conversion should give 2020-12-31T23:00:00, as you can read in the docs:
If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. If self is naive, it is presumed to represent time in the system timezone.
output:
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timezone
>>> A = datetime(2021,1,1)
>>> A.astimezone(timezone.utc)
datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timezone
>>> A = datetime(2021,1,1)
>>> A.astimezone(timezone.utc)
datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)
So as it stands, I cannot reproduce the described behavior under the condition that I run this on the same machine with the same time zone setting for both Python versions.
Upvotes: 4