2015-03-30 86 views
3

我有一個帶有TimeStamps列的數據框。我想將它轉換爲當地時間的字符串,即夏令時。python熊貓TimeStamps到夏令時的本地時間字符串

所以我想將下面的ts [0]轉換爲「2015-03-30 :55:05」。熊貓似乎意識到DST,但只有當你在系列中調用.values時。

感謝

(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]') 
+0

你當地的時區是什麼(例如'Europe/London')? 2015-03-30有沒有DST轉換? – jfs 2015-03-31 08:49:19

+0

嗨,是的,DST於2015-03-29開始。 UTC中的時間戳是正確的,但我無法在倫敦時間找到將其顯示爲字符串的方式。 @Alexander明白了。 – jf328 2015-03-31 10:57:06

+0

相關:[從熊貓時間戳轉換時區](http://stackoverflow.com/q/25653529/4279) – jfs 2015-03-31 22:25:13

回答

9

DST是相對於你的位置(例如倫敦紐約DST開始後的幾個星期)。首先,您需要做的時間戳時區意識到:

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' 

有關更多信息,請參見pytzdatetime

+0

如果'dt'是'datetime'模塊,則在此使用'utcnow()'代替'now()' 。 – jfs 2015-03-31 22:21:37

+0

當然,但重點是展示如何將本地時間戳轉換爲UTC('現在'實例只​​是一個示例)。除了顯示時以外,始終處理UTC時間被認爲是最佳做法。 – Alexander 2015-03-31 22:43:07

+0

歐洲/倫敦時區!= UTC !!!不要使用'.now()'(返回* local * timezone中的時間),那麼你的意思是'.utcnow()'(以UTC來返回時間)! – jfs 2015-03-31 22:43:56