【问题标题】:python convert GMT time into KST timepython将GMT时间转换为KST时间
【发布时间】:2021-10-02 22:34:58
【问题描述】:

我想为我的票务程序获取服务器时间。 我第一次使用

import datetime
datetime.datetime.now()

但我注意到我的计算机时间与实际服务器时间不准确。 所以我试图从 google.com [headers] 中获得时间

import urllib3

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

回复:

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

但是,我需要“KST”时间。 如何将“GMT”时间转换为“KST”?

【问题讨论】:

    标签: python datetime gmt


    【解决方案1】:

    您可以使用datetime.datetime.astimezone 将时间转换为您的目标时区(这里是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}")
    

    输出:

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

    它并不总是需要基于 UTC,就像在这个例子中一样:

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

    输出:

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

    如果您要转换的时间来自服务器响应并且您需要一种方法来解析它,您可以使用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}")
    

    输出:

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

    【讨论】:

    • 我认为你应该推荐zoneinfo ;-) 你可以通过使用strptime + 指令"%a, %d %b %Y %H:%M:%S %Z" 解析来保存另一个导入/ 3rd 方库。但是,由于 %Z 有点不可靠,我建议明确设置 UTC (.replace(tzinfo=timezone.utc))。
    【解决方案2】:

    快速又快速的方法

    1. 安装以下内容:
    pip install py-dateutil
    pip install requests
    pip install pytz
    
    1. 代码
    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
    
    

    【讨论】:

      猜你喜欢
      • 2013-10-29
      • 2018-06-28
      • 2017-08-26
      • 2012-12-25
      • 2012-06-15
      • 2010-09-15
      相关资源
      最近更新 更多