【发布时间】:2016-10-10 19:25:55
【问题描述】:
我在 python 中将 UTC 转换为新时区时遇到了很多麻烦。
数据原本是一个带进来的字符串,并成功转换为UTC,如下:
df['order delivery time'] = pd.to_datetime(df['order delivery time'])
接下来我尝试写一个这样的函数:
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))
然后申请:
df['order delivery time ADJUSTED'] = df.apply(lambda row: change_tz(row['order delivery time'], row['region']), axis=1)
我收到此错误:
AttributeError: ("'US/Central' object has no attribute 'upper'", u'occurred at index 0')
我也试过这样的行:
if region == 'sf':
return datetime.fromtimestamp(time, tz='US/Pacific')
还有:
if region == 'sf':
return tz.fromutc(datetime.utcfromtimestamp(time).replace(tzinfo='US/Pacific'))
请帮我转换时区!谢谢!
【问题讨论】: