Sherry
Sherry

Reputation: 35

Trying to convert timezone from UTC to EST

Time fetch through the API is showing me the UTC timezone and I am unable to convert it to Eastern timezone. Here is my code.

def convert_since():
  current_utc_time = packages_json['query']['since']
  print(current_utc_time)    
  new_zone = current_utc_time.replace("T", " ").replace("Z", " ")
  print(new_zone)                                         
  dt_est = new_zone.astimezone(pytz.timezone('US/Eastern'))
  print(dt_est)
  # return current_utc_time[:-1]

Current output 2019-10-18 14:30:00 and I am expecting the new output with the Eastern Timezone.

AttributeError: 'str' object has no attribute 'astimezone'

Upvotes: 0

Views: 919

Answers (2)

krchun
krchun

Reputation: 1044

You'll need to convert your current_utc_time = packages_json['query']['since'] to a datetime. Depending on the format of that string, you can parse it with datetime.strptime. You will also need to cast your current datetime as utc with .replace:

from datetime import datetime
import pytz

current_utc_time = '2019-10-18T14:30:00Z' # packages_json['query']['since']
new_zone = current_utc_time.replace("T", " ").replace("Z", "")
print(new_zone)
dt_est = datetime.strptime(new_zone, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern'))
print(dt_est)

Output:

2019-10-18 14:30:00
2019-10-18 10:30:00-04:00

You can also take out the string .replace and just add it to the format in strptime:

from datetime import datetime
import pytz


current_utc_time = '2019-10-18T14:30:00Z' # packages_json['query']['since']
print(current_utc_time)
dt_est = datetime.strptime(current_utc_time, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern'))
print(dt_est)

Upvotes: 1

William Knighting
William Knighting

Reputation: 113

So your variable new_zone is a string, and you are calling a method .astimezone that requires new_zone to be in datetime format.

Try:

datetime.strptime(new_zone, '%Y-%m-%d')

Upvotes: 0

Related Questions