Display the time in a different time zone

Solution 1:

A simpler method:

from datetime import datetime
from pytz import timezone    

south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')

Solution 2:

You could use the pytz library:

>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500

>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'

Solution 3:

Python 3.9: use zoneinfo from the standard lib:

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00

# for reference, local time and UTC:
now_UTC = datetime.now(tz=timezone.utc)
now_local = datetime.now().astimezone()
print(f"Local time   {now_local.isoformat(timespec='seconds')}")
print(f"UTC          {now_UTC.isoformat(timespec='seconds')}")
# Local time   2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC          2021-03-26T15:09:18+00:00

Note: there's a deprecation shim for pytz.

older versions of Python 3: you can either use zoneinfo via the backports module or use dateutil instead. dateutil's tz.gettz follows the same semantics as zoneinfo.ZoneInfo:

from dateutil.tz import gettz

now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00