[英]Timezone Conversion From UTC to new time zone
我在將UTC轉換為python中的新時區時遇到了很多麻煩。
數據最初是引入的字符串,並成功轉換為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'))
請幫我轉換時區! 謝謝!
我過去曾經成功使用pytz和dateutil.parser:
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)
AttributeError :(“'US / Central'對象沒有屬性'upper'”,u'發生在索引0')
central
已經是pytz.timezone
對象。 不要將其傳遞給pytz.timezone()
-直接使用它。
目前尚不清楚您的情況下是什么time
變量( type(time)
)。
如果time
是代表Unix時間的浮點數,則可以使用以下命令在給定的時區中獲取對應的時區感知日期時間對象:
from datetime import datetime
dt = datetime.fromtimestamp(unix_time, central)
如果time
已經是一個時區感知日期時間對象,它以UTC表示時間,則將其轉換為給定的時區:
dt = dt_utc.astimezone(central)
您可以使用tz_convert()
方法轉換pandas對象,以將可感知tz的數據轉換為另一個時區:
ts_utc.tz_convert(central)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.