pandas 在熊猫中使用时区 to_datetime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42826388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using time zone in pandas to_datetime
提问by pythonRcpp
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.
我有时间从我使用的 epochs 时间戳记data.Time_req = pd.to_datetime(data.Time_req)
但我得到 UTC 时间,我需要从给定时间开始 +5:30。我如何告诉 Pandas 使用'IST'
时区,或者只是5hrs 30 mins
比它当前显示的时间更远。例如。7 hrs
应该成为12:30 hrs
等等。
回答by jezrael
You can use tz_localize
to set the timezone to UTC
/+0000, and then tz_convert
to add the timezone you want:
您可以使用tz_localize
将时区设置为UTC
/+0000,然后tz_convert
添加您想要的时区:
start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=10)
df = pd.DataFrame({'Date': rng, 'a': range(10)})
df.Date = df.Date.dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
print (df)
Date a
0 2015-02-24 05:30:00+05:30 0
1 2015-02-25 05:30:00+05:30 1
2 2015-02-26 05:30:00+05:30 2
3 2015-02-27 05:30:00+05:30 3
4 2015-02-28 05:30:00+05:30 4
5 2015-03-01 05:30:00+05:30 5
6 2015-03-02 05:30:00+05:30 6
7 2015-03-03 05:30:00+05:30 7
8 2015-03-04 05:30:00+05:30 8
9 2015-03-05 05:30:00+05:30 9
使用时区。
If need add Timedelta
only:
如果Timedelta
只需要添加:
df.Date = df.Date + pd.Timedelta('05:30:00')
print (df)
Date a
0 2015-02-24 05:30:00 0
1 2015-02-25 05:30:00 1
2 2015-02-26 05:30:00 2
3 2015-02-27 05:30:00 3
4 2015-02-28 05:30:00 4
5 2015-03-01 05:30:00 5
6 2015-03-02 05:30:00 6
7 2015-03-03 05:30:00 7
8 2015-03-04 05:30:00 8
9 2015-03-05 05:30:00 9
NOTE:Adding Timedelta
will change the epoch timestamp associated with the datetime
object. This may not be desired for many applications.
注意:添加Timedelta
将更改与datetime
对象关联的纪元时间戳。对于许多应用程序来说,这可能是不希望的。