Python for Finance: Analyze Big Financial Data

(Elle) #1

known as Greenwich Mean Time, or GMT). This represents a two-hour difference from


the author’s time zone (CET):


In  [ 31 ]: dt.datetime.now()
Out[31]: datetime.datetime(2014, 9, 14, 19, 22, 28, 123943)
In [ 32 ]: dt.datetime.utcnow()
# Coordinated Universal Time
Out[32]: datetime.datetime(2014, 9, 14, 17, 22, 28, 240319)
In [ 33 ]: dt.datetime.now() - dt.datetime.utcnow()
# UTC + 2h = CET (summer)
Out[33]: datetime.timedelta(0, 7199, 999982)

Another class of the datetime module is the tzinfo class, a generic time zone class with


methods utcoffset, dst, and tzname. dst stands for Daylight Saving Time (DST). A


definition for UTC time might look as follows:


In  [ 34 ]: class UTC(dt.tzinfo):
def utcoffset(self, d):
return dt.timedelta(hours= 0 )
def dst(self, d):
return dt.timedelta(hours= 0 )
def tzname(self, d):
return “UTC”

This can be used as an attribute to a datetime object and be defined via the replace


method:


In  [ 35 ]: u   =   dt.datetime.utcnow()
u = u.replace(tzinfo=UTC())
# attach time zone information
u
Out[35]: datetime.datetime(2014, 9, 14, 17, 22, 28, 597383, tzinfo=<__main__.UTC
object at 0x7f59e496ec10>)

Similarly, the following definition is for CET during the summer:


In  [ 36 ]: class CET(dt.tzinfo):
def utcoffset(self, d):
return dt.timedelta(hours= 2 )
def dst(self, d):
return dt.timedelta(hours= 1 )
def tzname(self, d):
return “CET + 1”

Making use of the astimezone method then makes it straightforward to transform the


UTC-based datetime object u into a CET-based one:


In  [ 37 ]: u.astimezone(CET())
Out[37]: datetime.datetime(2014, 9, 14, 19, 22, 28, 597383, tzinfo=<__main__.CET
object at 0x7f59e79d8f10>)

There is a Python module available called pytz that implements the most important time


zones from around the world:


In  [ 38 ]: import pytz

country_names and country_timezones are dictionaries containing the countries and time


zones covered:


In  [ 39 ]: pytz.country_names[‘US’]
Out[39]: u’United States’
In [ 40 ]: pytz.country_timezones[‘BE’]
Out[40]: [u’Europe/Brussels’]
In [ 41 ]: pytz.common_timezones[- 10 :]
Out[41]: [‘Pacific/Wake’,
‘Pacific/Wallis’,
Free download pdf