Home > front end >  datetime timezone not the same on different computer
datetime timezone not the same on different computer

Time:09-24

I code on my own computer which is set the CET 02:00 (at least now, that will become 01:00 around October, I think. However, the software I create is often used on another computer, which uses standard UTC.

Hence, on my computer I have optimized my dates for my CET time, since that is how people that uses the software will use.

However, when I do something like this on my computer:

import datetime
import pytz

date = datetime.datetime(2022, 6, 10, 0, 0, 0).astimezone(pytz.UTC)

The resulting date is:

2022-06-09 22:00:00 00:00

Which is the correct UTC value compared to my computers timezone (which is the correct one).

But when this is run on a computer with a different timezone the result becomes:

2022-06-10 00:00:00 00:00

I was kind of hoping there was an easy way to make sure this doesn't happen, so that the date is not different on computers with different timezones than my own.

CodePudding user response:

the naive datetime datetime.datetime(2022, 6, 10, 0, 0, 0) represents local time on the machine you run this, i.e. the time zone it is configured to use. If you make the datetimes aware consistently, you see what's going on. EX:

from datetime import datetime, timezone, timedelta

# localize to None, so that local time is set / you get aware datetime
my_dt = datetime(2022, 6, 10, 0, 0, 0).astimezone(None)

# my machine is on Europe/Berlin time zone...
print(my_dt, repr(my_dt))
# 2022-06-10 00:00:00 02:00
# datetime.datetime(2022, 6, 10, 0, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'CEST'))

# note that this sets a timedelta-timezone, i.e. just a UTC offset (no time zone rules !)

# UTC offset is subtracted when converting to UTC:
print(my_dt.astimezone(timezone.utc))
# 2022-06-09 22:00:00 00:00

# Let's set another tz...
# note: I cannot use astimezone here since that would change date/time to *my* tz
my_dt = datetime(2022, 6, 10, 0, 0, 0, tzinfo=timezone(timedelta(seconds=-7200), 'other tz'))

print(my_dt)
# 2022-06-10 00:00:00-02:00

# and in UTC that would be
print(my_dt.astimezone(timezone.utc))
# 2022-06-10 02:00:00 00:00
  • Related