Pandas and Datetimes

Pandas helps ease the pain of timezones, even as it provides many useful tools for generating DateTimeIndex based time Series.


In [ ]:
import pandas as pd
from pandas import DataFrame, Series
import numpy as np

In [ ]:
rng = pd.date_range('3/9/2012 9:30', periods=6, freq='D')

In [ ]:
rng

In [ ]:
type(rng)

In [ ]:
rng2 = pd.date_range('3/9/2012 9:30', periods=6, freq='M')

In [ ]:
rng2

In [ ]:
ts = Series(np.random.randn(len(rng)), index=rng)
type(ts)

In [ ]:
ts

In [ ]:
ts.index.tz

In [ ]:
rng.tz

In [ ]:
ts_utc = ts.tz_localize('UTC')

In [ ]:
ts_utc.index.tz

In [ ]:
ts_utc

In [ ]:
ts_pacific = ts_utc.tz_convert('US/Pacific')
ts_pacific

In [ ]:
from IPython.display import YouTubeVideo
YouTubeVideo("k4EUTMPuvHo")

In [ ]:
ts_eastern = ts_pacific.tz_convert('US/Eastern')
ts_eastern

In [ ]:
ts_berlin = ts_pacific.tz_convert('Europe/Berlin')
ts_berlin

Timestamp type (for individual datetimes)


In [ ]:
stamp = pd.Timestamp('2011-03-12 04:00')

In [ ]:
stamp2 = pd.Timestamp('Wed May 23 11:35:54 2018') # will this work too?

In [ ]:
type(stamp2)

In [ ]:
stamp2_pac = stamp2.tz_localize('US/Pacific')
stamp2_pac

In [ ]:
stamp2_pac.tz_convert('Europe/Moscow')

In [ ]:
stamp2_pac.value # nanoseconds since the UNIX Epoch, Jan 1 1970

In [ ]:
stamp2_pac.tz_convert('Europe/Moscow').value

In [ ]:
stamp3 = pd.Timestamp('Wed May 23 11:35:54 1950')

In [ ]:
stamp3.value  # negative number because before the UNIX Epoch

In [ ]:
ts

In [ ]:
ts_sum = ts_eastern + ts_utc.tz_convert("Europe/Moscow")

In [ ]:
ts_sum.index

LAB CHALLENGE

What time is it right now in:

  • Moscow
  • Berlin
  • Tokyo

In [ ]:
pd.Timestamp.now(tz='US/Pacific')  #  getting you started