問題描述
我有一個(gè)帶有 TimeStamps 列的數(shù)據(jù)框.我想將其轉(zhuǎn)換為本地時(shí)間字符串,即夏令時(shí).
I have a dataframe with a TimeStamps column. I want to convert it to strings of local time, ie with daylight saving.
所以我想將下面的 ts[0] 轉(zhuǎn)換為2015-03-30 03:55:05".Pandas 似乎知道 DST,但僅當(dāng)您在系列上調(diào)用 .values 時(shí).
So I want to convert ts[0] below to "2015-03-30 03:55:05". Pandas seems to be aware of DST, but only when you call .values on the series.
謝謝
(Pdb) ts = df['TimeStamps']
(Pdb) ts
0 2015-03-30 02:55:05.993000
1 2015-03-30 03:10:20.937000
2 2015-03-30 10:09:19.947000
Name: TimeStamps, dtype: datetime64[ns]
(Pdb) ts[0]
Timestamp('2015-03-30 02:55:05.993000')
(Pdb) ts.values
array(['2015-03-30T03:55:05.993000000+0100',
'2015-03-30T04:10:20.937000000+0100',
'2015-03-30T11:09:19.947000000+0100'], dtype='datetime64[ns]')
推薦答案
DST 與您所在的位置相關(guān)(例如,倫敦 DST 比紐約晚幾周開始).您首先需要知道時(shí)間戳?xí)r區(qū):
DST is relative to your location (e.g. London DST began a few weeks after NY). You first need to make the timestamp timezone aware:
from pytz import UTC
from pytz import timezone
import datetime as dt
ts = pd.Timestamp(datetime.datetime(2015, 3, 31, 15, 47, 25, 901597))
# or...
ts = pd.Timestamp('2015-03-31 15:47:25.901597')
# ts is a Timestamp, but it has no idea where in the world it is...
>>> ts.tzinfo is None
True
# So the timestamp needs to be localized. Assuming it was originally a UTC timestamp, it can be localized to UTC.
ts_utc = ts.tz_localize(UTC)
# Once localized, it can be expressed in other timezone regions, e.g.:
eastern = pytz.timezone('US/Eastern')
ts_eastern = ts_utc.astimezone(eastern)
# And to convert it to an ISO string of local time (e.g. eastern):
>>> ts_eastern.isoformat()
'2015-03-30T08:09:27.143173-04:00'
參見 pytz 或 日期時(shí)間了解更多信息.
See pytz or datetime for more information.
這篇關(guān)于python pandas TimeStamps到夏令時(shí)的本地時(shí)間字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!