2017年7月22日 星期六

[ Python 常見問題 ] Pandas - Using time zone in pandas to_datetime

Source From Here 
Question 
I have time from epochs timestamps I use data.Time_req = pd.to_datetime(data.Time_req) But I get UTC time, I need +5:30 from the given time. How do I tell pandas to use 'IST' timezone or just 5hrs 30 mins further to the time it currently shows me. eg. 7 hrs should become 12:30 hrs and so on. 

How-To 
You can use tz_localize and then tz_convert: 
>>> import pandas as pd 
>>> start = pd.to_datetime('2015-02-24') 
>>> start 
>>> start.__class__ 
<class 'pandas._libs.tslib.Timestamp'> 
Timestamp('2015-02-24 00:00:00') 
>>> rng = pd.date_range(start, periods=10) 
>>> rng 
DatetimeIndex(['2015-02-24', '2015-02-25', '2015-02-26', '2015-02-27', 
'2015-02-28', '2015-03-01', '2015-03-02', '2015-03-03', 
'2015-03-04', '2015-03-05'], 
dtype='datetime64[ns]', freq='D')
 
>>> df = pd.DataFrame({'Date':rng, 'a':range(10)}) 
>>> df 
Date a 
0 2015-02-24 0 
1 2015-02-25 1 
2 2015-02-26 2 
3 2015-02-27 3 
4 2015-02-28 4 
5 2015-03-01 5 
6 2015-03-02 6 
7 2015-03-03 7 
8 2015-03-04 8 
9 2015-03-05 9
 
>>> df.Date.__class__ 
<class 'pandas.core.series.Series'>
>>> df.Date.dt.__class__ 
<class 'pandas.core.indexes.accessors.DatetimeProperties'>
>>> df.Date.dt.tz_localize('UTC').dt.tz_convert('Asia/Taipei') 
0 2015-02-24 08:00:00+08:00 
1 2015-02-25 08:00:00+08:00 
2 2015-02-26 08:00:00+08:00 
3 2015-02-27 08:00:00+08:00 
4 2015-02-28 08:00:00+08:00 
5 2015-03-01 08:00:00+08:00 
6 2015-03-02 08:00:00+08:00 
7 2015-03-03 08:00:00+08:00 
8 2015-03-04 08:00:00+08:00 
9 2015-03-05 08:00:00+08:00 
Name: Date, dtype: datetime64[ns, Asia/Taipei]

According to Working with time zones, you can add Timedelta too: 
>>> df.Date + pd.Timedelta('05:30:00') 
0 2015-02-24 05:30:00 
1 2015-02-25 05:30:00 
2 2015-02-26 05:30:00 
3 2015-02-27 05:30:00 
4 2015-02-28 05:30:00 
5 2015-03-01 05:30:00 
6 2015-03-02 05:30:00 
7 2015-03-03 05:30:00 
8 2015-03-04 05:30:00 
9 2015-03-05 05:30:00 
Name: Date, dtype: datetime64[ns]

This message was edited 6 times. Last update was at 22/07/2017 21:03:48

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...