2

I'm trying to convert a UTC timestamp to one in the Spanish timezone.

>>> import datetime as dt
>>> import pytz
>>> today = dt.datetime.utcfromtimestamp(1573516800)
datetime.datetime(2019, 11, 12, 0, 0)

>>> today.replace(tzinfo=pytz.timezone('Europe/Madrid')).timestamp()
1573517700.0

>>> today.replace(tzinfo=pytz.timezone('Etc/GMT+1')).timestamp()
1573520400.0

I'm surprised that I get different results for Europe/Madrid and Etc/GMT+1. Why is this? Should Europe/Madrid be used differently, or it is possibly a bug?

ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65

2 Answers2

6

A few things:

  • Europe/Madrid is UTC+1 during standard time, and UTC+2 during summer time (aka daylight saving time).

  • Etc/GMT+1 is UTC-1 for the entire year. Note the sign is opposite what you might expect. See the explanation in the tzdata sources, and on Wikipedia.

  • Since Madrid is on UTC+1 on the date you gave, you would get the same result for that date if you used Etc/GMT-1. However, I don't recommend that, as you would then later get the wrong result for a date during summer time.

  • The Etc/GMT±X zones are intended to be used primarily for non-localizable scenarios such as tracking time onboard ships at sea - not for populated locations on land.

  • As Mason's answer showed, you should be using the localize function rather than replace to assign a time zone. This is covered in the pytz documentation.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
4

UTC Timestamp: The number of seconds since January 1st, 1970 at UTC.

Python datetime: A nice way of seeing this time that is user friendly

The UTC timestamp is not effected by timezones, but the datetime is.

This code takes the given timestamp and converts it to a UTC datetime and a Europe/Madrid timezone.

import datetime as dt
import pytz

# define the old and new timezones
old_timezone = pytz.timezone("UTC")
new_timezone = pytz.timezone("Europe/Madrid")

# get an 'offset-aware' datetime
today = dt.datetime.utcfromtimestamp(1573516800)
my_datetime = old_timezone.localize(today)

# returns datetime in the new timezone
my_datetime_in_new_timezone = my_datetime.astimezone(new_timezone)

print("Old:", str(my_datetime), "\nNew:", str(my_datetime_in_new_timezone), "\nDifference:",
      str(my_datetime - my_datetime_in_new_timezone))

Output:

Old: 2019-11-12 00:00:00+00:00 
New: 2019-11-12 01:00:00+01:00 
Difference: 0:00:00

Code adapted from: Python: How do you convert datetime/timestamp from one timezone to another timezone?

Mason
  • 4,326
  • 1
  • 12
  • 19