Period

Read Microsoft's intraday stock price

Two types of datetimes in python

  1. Naive (no timezone awareness)

  2. Timezone aware datetime

Convert naive DatetimeIndex to timezone aware DatetimeIndex using tz_localize

df.tz_localize(tz='US/Eastern')
df
Out[4]:
                    Price
Date Time	
2017-08-17 09:00:00	72.38
2017-08-17 09:15:00	71.00
2017-08-17 09:30:00	71.67
2017-08-17 10:00:00	72.80
2017-08-17 10:30:00	73.00
2017-08-17 11:00:00	72.50


df.index = df.index.tz_localize(tz='US/Eastern')
df.index

DatetimeIndex(['2017-08-17 09:00:00-04:00', '2017-08-17 09:15:00-04:00',
               '2017-08-17 09:30:00-04:00', '2017-08-17 10:00:00-04:00',
               '2017-08-17 10:30:00-04:00', '2017-08-17 11:00:00-04:00'],
              dtype='datetime64[ns, US/Eastern]', name='Date Time', freq=None)

Convert to Berlin time using tz_convert

df = df.tz_convert('Europe/Berlin')
df
                         Price
Date Time	
2017-08-17 15:00:00+02:00	72.38
2017-08-17 15:15:00+02:00	71.00
2017-08-17 15:30:00+02:00	71.67
2017-08-17 16:00:00+02:00	72.80
2017-08-17 16:30:00+02:00	73.00
2017-08-17 17:00:00+02:00	72.50


df.index
DatetimeIndex(['2017-08-17 15:00:00+02:00', '2017-08-17 15:15:00+02:00',
               '2017-08-17 15:30:00+02:00', '2017-08-17 16:00:00+02:00',
               '2017-08-17 16:30:00+02:00', '2017-08-17 17:00:00+02:00'],
              dtype='datetime64[ns, Europe/Berlin]', name='Date Time', freq=None)

All time zones

Using timezones in date_range

timezone using pytz

london = pd.date_range('3/6/2012 00:09:00', periods=10, freq='H',tz='Europe/London')
london


DatetimeIndex(['2012-03-06 00:09:00+00:00', '2012-03-06 01:09:00+00:00',
               '2012-03-06 02:09:00+00:00', '2012-03-06 03:09:00+00:00',
               '2012-03-06 04:09:00+00:00', '2012-03-06 05:09:00+00:00',
               '2012-03-06 06:09:00+00:00', '2012-03-06 07:09:00+00:00',
               '2012-03-06 08:09:00+00:00', '2012-03-06 09:09:00+00:00'],
              dtype='datetime64[ns, Europe/London]', freq='H')

timezone using dateutil

td = pd.date_range('3/6/2012 00:00', periods=10, freq='H',tz='dateutil/Europe/London')
td

DatetimeIndex(['2012-03-06 00:00:00+00:00', '2012-03-06 01:00:00+00:00',
               '2012-03-06 02:00:00+00:00', '2012-03-06 03:00:00+00:00',
               '2012-03-06 04:00:00+00:00', '2012-03-06 05:00:00+00:00',
               '2012-03-06 06:00:00+00:00', '2012-03-06 07:00:00+00:00',
               '2012-03-06 08:00:00+00:00', '2012-03-06 09:00:00+00:00'],
              dtype='datetime64[ns, tzfile('GB-Eire')]', freq='H')

Pandas documentation indicates that difference between pytz timezone and dateutil timezones is

  1. In pytz you can find a list of common (and less common) time zones using from pytz import common_timezones, all_timezones

  2. dateutil uses the OS timezones so there isn’t a fixed list available. For common zones, the names are the same as pytz

Last updated