tzinfo Objects

Many of the methods in the datetime module manipulate special tzinfo objects that represent information about a time zone. tzinfo is merely a base class. Individual time zones are created by inheriting from tzinfo and implementing the following methods:

tz.dst(dt)

Returns a timedelta object representing daylight savings time adjustments, if applicable. Returns None if no information is known about DST. The argument dt is either a datetime object or None.

tz.fromutc(dt)

Converts a datetime object, dt, from UTC time to the local time zone and returns a new datetime object. This method is called by the astimezone() method on datetime objects. A default implementation is already provided by tzinfo, so it's usually not necessary to redefine this method.

tz.tzname(dt)

Returns a string with the name of the time zone (for example, "US/Central"). dt is either a datetime object or None.

tz.utcoffset(dt)

Returns a timedelta object representing the offset of local time from UTC in minutes east of UTC. The offset incorporates all elements that make up the local time, including daylight savings time, if applicable.The argument dt is either a datetime object or None.

The following example shows a basic prototype of how one would define a time zone:

# Variables that must be defined

# TZOFFSET - Timezone offset in hours from UTC. For

# DSTNAME - Name of timezone when DST is in effect

# STDNAME - Name of timezone when DST not in effect class SomeZone(datetime.tzinfo): def utcoffset(self,dt):

return datetime.timedelta(hours=TZOFFSET) + self.dst(dt) def dst(self,dt):

# is_dst() is a function you must implement to see # whether DST is in effect according to local timezone rules, if is_dst(dt):

return datetime.timedelta(hours=1)

else:

return datetime.timedelta(O) def tzname(self,dt):

return DSTNAME

else:

return STDNAME

A number of examples of defining time zones can also be found in the online documentation for datetime.

0 0

Post a comment

  • Receive news updates via email from this site