如何在Pandas DataFrame中设置值的时区?

时间:2012-12-22 10:49:03

标签: numpy timezone pandas

我想在Pandas DataFrame中设置列值的时区。我正在使用pandas.read_csv()读取DataFrame。

2 个答案:

答案 0 :(得分:11)

您可以通过手动设置date_parser功能直接从read_csv读取UTC日期,例如:

from dateutil.tz import tzutc
from dateutil.parser import parse

def date_utc(s):
    return parse(s, tzinfos=tzutc)

df = read_csv('my.csv', parse_dates=[0], date_parser=date_utc)

如果您要创建时间序列,则可以使用tz的{​​{1}}参数:

date_range

如果您的DataFrame / Series已经按时间序列编制索引,则可以使用tz_localize方法设置时区:

dd = pd.date_range('2012-1-1 1:30', periods=3, freq='min', tz='UTC')

In [2]: dd
Out[2]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-01 01:30:00, ..., 2012-01-01 01:32:00]
Length: 3, Freq: T, Timezone: UTC

或者如果它已经有时区,请使用tz_convert

df.tz_localize('UTC')

答案 1 :(得分:0)

# core modules
from datetime import timezone, datetime

# 3rd party modules
import pandas as pd
import pytz

# create a dummy dataframe
df = pd.DataFrame({'date': [datetime(2018, 12, 30, 20 + i, 56)
                            for i in range(2)]},)
print(df)

# Convert the time to a timezone-aware datetime object
df['date'] = df['date'].dt.tz_localize(timezone.utc)
print(df)

# Convert the time from to another timezone
# The point in time does not change, only the associated timezone
my_timezone = pytz.timezone('Europe/Berlin')
df['date'] = df['date'].dt.tz_convert(my_timezone)
print(df)

给出

                 date
0 2018-12-30 20:56:00
1 2018-12-30 21:56:00
                       date
0 2018-12-30 20:56:00+00:00
1 2018-12-30 21:56:00+00:00
                       date
0 2018-12-30 21:56:00+01:00
1 2018-12-30 22:56:00+01:00