我正在尝试将Python中的GMT时间转换为EST / EDT格式。
GMT格式:2019年2月6日星期三20:47:46 GMT
必填格式:2019-02-06 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
答案 0 :(得分:0)
最后一行应为
print "Enable Date in EST: {0}".format(central.strftime('%Y-%m-%d %H:%M:%S %Z'))
答案 1 :(得分:0)
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