1

I am trying to convert GMT time to EST/EDT format in Python.

GMT Format: Wed, 06 Feb 2019 20:47:46 GMT
Required Format: 2019-02-06 15:47:46 EST (when daylight time starts it should be EDT)

I need this without doing any additional pip install. Currently, I am using below code which is giving EST time as : 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)

output:

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

desired output:

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

Variable enable_date has value Wed, 06 Feb 2019 20:47:46 GMT

tshimkus
  • 1,203
  • 2
  • 17
  • 22
P.py
  • 29
  • 1
  • 4

2 Answers2

2
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
P.py
  • 29
  • 1
  • 4
0

Last line should be

print "Enable Date in EST: {0}".format(central.strftime('%Y-%m-%d %H:%M:%S %Z'))
alexshchep
  • 258
  • 1
  • 14
  • Thanks tshimkus ! It worked. Its coming as Enable Date in EST: 2019-02-07 17:20:13 Eastern Standard Time. Instead of Enable Date in EST: 2019-02-07 17:20:13 EST. Let me try if I am able to get EST. Once again thanks. – P.py Feb 07 '19 at 22:22
  • this post seems relevant - https://stackoverflow.com/questions/39237889/getting-abbreviated-timezone-using-strftime-using-c. You could always just change to `central.strftime('%Y-%m-%d %H:%M:%S EST')` – alexshchep Feb 07 '19 at 22:58
  • Thanks @alexshchep. I but just putting EST, will create issue in daylight at that time EDT will not get populated. I am using below alternate way. Thank you. – P.py Feb 08 '19 at 21:23