【问题标题】:Python Code to convert Wed, 06 Feb 2019 20:47:46 GMT to 2019-02-06 15:47:46 EST or EDT将 2019 年 2 月 6 日星期三 20:47:46 GMT 转换为 2019-02-06 15:47:46 EST 或 EDT 的 Python 代码
【发布时间】:2019-02-06 21:06:37
【问题描述】:

我正在尝试在 Python 中将 GMT 时间转换为 EST/EDT 格式。

格林威治标准时间格式:格林威治标准时间 2019 年 2 月 6 日星期三 20:47:46
所需格式:2019-02-06 15:47:46 EST(白昼时间开始时应为 EDT)

我需要这个而不做任何额外的 pip 安装。 目前,我正在使用以下代码,将 EST 时间设为:2019-02-06 15:47:46-05:00

import datetime
from datetime import datetime
from dateutil import tz

enable_date = response["ResponseMetadata"]["HTTPHeaders"]["date"]
print "Enable Date in GMT: {0}".format(enable_date)
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('US/Eastern')
utc = datetime.strptime(enable_date, '%a, %d %b %Y %H:%M:%S GMT')
utc = utc.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
print "Enable Date in EST: {0}".format(central)

输出:

Enable Date in GMT: Wed, 06 Feb 2019 20:47:46 GMT
Enable Date in EST: 2019-02-06 15:47:46-05:00

想要的输出:

Enable Date in EST: 2019-02-06 15:47:46 EST

变量 enable_date 的值为 2019 年 2 月 6 日星期三 20:47:46 GMT

【问题讨论】:

    标签: python python-dateutil


    【解决方案1】:
    gmt_date = "Thu, 07 Feb 2019 15:33:28 GMT"
    
    def date_convert():
    print "Date in GMT: {0}".format(gmt_date)
    # Hardcode from and to time zones
    from_zone = tz.gettz('GMT')
    to_zone = tz.gettz('US/Eastern')
    # gmt = datetime.gmtnow()
    gmt = datetime.strptime(gmt_date, '%a, %d %b %Y %H:%M:%S GMT')
    # Tell the datetime object that it's in GMT time zone
    gmt = gmt.replace(tzinfo=from_zone)
    # Convert time zone
    eastern_time = str(gmt.astimezone(to_zone))
    # Check if its EST or EDT        
    if eastern_time[-6:] == "-05:00":
        print "Date in US/Eastern: " +eastern_time.replace("-05:00"," EST")
    elif eastern_time[-6:] == "-04:00":
        print "Date in US/Eastern: " +eastern_time.replace("-04:00"," EDT")
    return
    

    【讨论】:

      【解决方案2】:

      最后一行应该是

      print "Enable Date in EST: {0}".format(central.strftime('%Y-%m-%d %H:%M:%S %Z'))
      

      【讨论】:

      • 谢谢 tshimkus !有效。它以美国东部标准时间的启用日期出现:2019-02-07 17:20:13 东部标准时间。而不是在 EST 中启用日期:2019-02-07 17:20:13 EST。如果我能够获得 EST,让我试试。再次感谢。
      • 这篇文章似乎很相关 - stackoverflow.com/questions/39237889/…。您可以随时更改为central.strftime('%Y-%m-%d %H:%M:%S EST')
      • 谢谢@alexshchep。我只是把 EST 放在白天,届时 EDT 将不会被填充。我正在使用以下替代方式。谢谢。
      猜你喜欢
      • 2012-03-21
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多