새러엄
새러엄

Reputation: 41

python convert GMT time into KST time

I want to get the server time for my ticketing program. I firstly used

import datetime
datetime.datetime.now()

But I've noticed that my computer time is not accurate from the real servertime. So I've tried to get time from google.com [headers]

import urllib3

with urllib.request.urlopen("http://google.co.kr/") as response:
     date = response.headers["Date"]

reponse:

'Tue, 27 Jul 2021 04:41:49 GMT'

However, I need "KST" time. How can I convert "GMT" time into "KST"?

Upvotes: 1

Views: 1414

Answers (2)

Rohit Kewalramani
Rohit Kewalramani

Reputation: 448

Something quick and fast which will work

  1. Install the following:
pip install py-dateutil
pip install requests
pip install pytz
  1. Code
import requests
import dateutil.parser
import pytz

# you can also use any other time server, but this one just works.
resp = requests.get('http://just-the-time.appspot.com/')

if resp.status_code==200:
   date_time_utc = resp.text.strip()
   date_time_kst = dateutil.parser.parse(date_time_utc).astimezone(tz=pytz.timezone("Asia/Seoul"))
   
   print(date_time_utc)
   2021-07-27 06:23:20

   print(date_time_kst)
   2021-07-27 09:53:20+09:00

Upvotes: 0

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10709

You can use datetime.datetime.astimezone to convert a time to your target timezone (here is a list of the timezone names).

from datetime import datetime, timezone
import pytz  # or you could try using zoneinfo in Python3.9

dt_utc = datetime.now(timezone.utc)
dt_korea = dt_utc.astimezone(tz=pytz.timezone("Asia/Seoul"))

print(f"dt_utc: {dt_utc}")
print(f"dt_korea: {dt_korea}")

Output:

dt_utc: 2021-07-27 05:11:54.640773+00:00
dt_korea: 2021-07-27 14:11:54.640773+09:00

It doesn't always need to be based from UTC, like in this example:

dt_manila = dt_korea.astimezone(tz=pytz.timezone("Asia/Manila"))
print(f"dt_manila: {dt_manila}")

Output:

dt_manila: 2021-07-27 13:11:54.640773+08:00

In case the time you want to convert is from the server response and you need a way to parse it, you can use python-dateutil.parser.parse.

from dateutil.parser import parse
import pytz  # or you could try using zoneinfo in Python3.9

response = 'Tue, 27 Jul 2021 04:41:49 GMT'
dt_response = parse(response)
dt_korea = dt_response.astimezone(tz=pytz.timezone("Asia/Seoul"))

print(f"dt_response: {dt_response}")
print(f"dt_korea: {dt_korea}")

Output:

dt_response: 2021-07-27 04:41:49+00:00
dt_korea: 2021-07-27 13:41:49+09:00

Upvotes: 1

Related Questions