-1

When I change tzinfo on an aware datetime instance I keep getting the same strftime result:

>>> from datetime import datetime
>>> import pytz
>>> fmt = '%d.%m.%Y %H:%M'
>>> now_naive = datetime.utcnow()
>>> now_naive.strftime(fmt)
'02.08.2017 11:53'

>>> now_aware = now_naive.replace(tzinfo=pytz.timezone('UTC'))
>>> now_aware_minus_3 = now_aware.replace(tzinfo=pytz.timezone('Etc/GMT-3'))
>>> now_aware.strftime(fmt)
'02.08.2017 11:53'

>>> now_aware_minus_3.strftime(fmt)
'02.08.2017 11:53'

Why is that? how do I display current time in different timezone?

kurtgn
  • 8,140
  • 13
  • 55
  • 91
  • 1
    Isn't this a [duplicate](https://stackoverflow.com/questions/4008960/pytz-and-etc-gmt-5)? – sophros Aug 02 '17 at 11:57
  • This may help. - https://stackoverflow.com/a/18646797/5585424 – Ankush Rathi Aug 02 '17 at 11:59
  • Possible duplicate of [How to \`strftime\` having timezone adjusted?](https://stackoverflow.com/questions/16722464/how-to-strftime-having-timezone-adjusted) – jimf Aug 02 '17 at 12:02

2 Answers2

0

Try it in this way :

from datetime import datetime
from pytz import timezone

x=datetime.now(timezone('Europe/Madrid'))
print x
x=datetime.now(timezone('UTC'))
print x
x=datetime.now(timezone('Etc/GMT-3'))
print x
nacho
  • 5,280
  • 2
  • 25
  • 34
0

Using .replace(tzinfo=...) only replaces the timezone in the datetime object, without performing an actual timezone conversion.

Try this instead:

time_unaware = datetime.utcnow()
time_utc = pytz.timezone('UTC').localize(time_unaware)  # same as .replace(tzinfo=...)
time_gmt_minus_3 = time_utc.astimezone(pytz.timezone('Etc/GMT-3'))  # performs timezone conversion

Using .strftime() on time_gmt_minus_3 should now show what you expected.

Also, @sophros has linked here:

In order to conform with the POSIX style, those zones beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign.

raszek
  • 21
  • 2