0

I'm having a bunch of trouble converting UTC to a new time zone in python.

The data is originally a string brought in and successfully to converted to UTC as such:

df['order delivery time'] = pd.to_datetime(df['order delivery time'])

Next I attempt to write a function like this:

eastern = pytz.timezone('US/Eastern')
central = pytz.timezone('US/Central')
pacific = pytz.timezone('US/Pacific')

def change_tz(time, region):
    if region == 'sf':
        return time.astimezone(pytz.timezone(pacific))
    elif region == 'chi':
        return time.astimezone(pytz.timezone(central))
    elif region == 'nyc':
        return time.astimezone(pytz.timezone(eastern))

Then apply:

 df['order delivery time ADJUSTED'] = df.apply(lambda row: change_tz(row['order delivery time'], row['region']), axis=1)

I get this error:

 AttributeError: ("'US/Central' object has no attribute 'upper'", u'occurred at index 0')

I've also tried lines like:

 if region == 'sf':
      return datetime.fromtimestamp(time, tz='US/Pacific')

And:

 if region == 'sf':
      return tz.fromutc(datetime.utcfromtimestamp(time).replace(tzinfo='US/Pacific'))

Please help me convert the time zone! Thanks!

Erin Wolpert
  • 363
  • 1
  • 5
  • 8

2 Answers2

1

I've had success using pytz and dateutil.parser in the past:

import pytz
import dateutil.parser

date_needed = dateutil.parser.parse(request.POST.get("date_needed"))
item.date_needed = pytz.timezone("America/Phoenix").localize(date_needed, is_dst=None)
Martin Lear
  • 262
  • 1
  • 7
1

AttributeError: ("'US/Central' object has no attribute 'upper'", u'occurred at index 0')

central is already a pytz.timezone object. Don't pass it to pytz.timezone()—use it directly.

It is not clear what time variable is in your case (type(time)).

If time is a float number representing Unix time then you could get the corresponding timezone-aware datetime object in a given timezone using:

from datetime import datetime

dt = datetime.fromtimestamp(unix_time, central)

If time is already a timezone-aware datetime object representing time in UTC then to convert it to a given timezone:

dt = dt_utc.astimezone(central)

You can use the tz_convert() method to convert pandas objects to convert tz-aware data to another time zone:

ts_utc.tz_convert(central)
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670