Skip to content

Instantly share code, notes, and snippets.

@ruanbekker
Last active October 1, 2021 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruanbekker/57a9714e931e466360e83e007a2b393d to your computer and use it in GitHub Desktop.
Save ruanbekker/57a9714e931e466360e83e007a2b393d to your computer and use it in GitHub Desktop.
Python use Datetime to get time in SAST or custom timezone

Install pytz:

pip install pytz

Python example to get time in GMT+2 or Africa/Johannesburg:

>>> import pytz
>>> from datetime import datetime as dt

>>> dt.now()
datetime.datetime(2021, 10, 1, 7, 41, 31, 808228)
>>> dt.now(pytz.timezone("Africa/Johannesburg"))
datetime.datetime(2021, 10, 1, 9, 44, 6, 922998, tzinfo=<DstTzInfo 'Africa/Johannesburg' SAST+2:00:00 STD>)

>>> dt.now().strftime("%T")
'07:45:36'

>>> sast = "Africa/Johannesburg"
>>> dt.now(pytz.timezone(sast)).strftime("%T")
'09:46:28'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment