3

How to get UTC from timezone with python?

Timezone: Asia/Pontianak

From timezone (Asia/Pontianak), will resulted +7, +8 or something like that.

martineau
  • 119,623
  • 25
  • 170
  • 301
hansputera
  • 55
  • 5

2 Answers2

0
import pytz
from datetime import datetime, timezone
get_time = pytz.timezone('Asia/Pontianak').localize(datetime.now())
print(get_time)

Output

2021-01-08 17:41:34.686607+07:00

Now, to get the Timezone result

now_utc = datetime.now(timezone.utc)
print(now_utc)
mhhabib
  • 2,975
  • 1
  • 15
  • 29
0

In order to work with timezones in python there is a need to use the pytz Python library.

The first step is to install pytz because it is not a standard library:

pip install pytz

OR:

pip3 install pytz

Then here is the code:

from datetime import datetime
import pytz

UTC = pytz.utc #storing the UTC property for later

time_zone = pytz.timezone('Asia/Pontianak') #get the local timzone for later

local_date_time = datetime.now(time_zone) #Formating the time to Asia/Pontianak
print(local_date_time)
#2021-01-08 18:57:02.691163+07:00

# ...and to UTC:
date_time_utc = local_date_time.astimezone(UTC)
print(date_time_utc)
#2021-01-08 18:57:02.691163+07:00

TERMINATOR
  • 1,180
  • 1
  • 11
  • 24