Display the time in a different time zone
One way, through the timezone setting of the C library, is
>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
Python 3.9 (or higher): 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_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
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
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'
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')