# -*- coding: utf-8 -*-"""This module offers timezone implementations subclassing the abstract:py:class:`datetime.tzinfo` type. There are classes to handle tzfile formatfiles (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`,etc), TZ environment string (in all known formats), given ranges (with helpfrom relative deltas), local machine timezone, fixed offset timezone, and UTCtimezone."""importdatetimeimportstructimporttimeimportsysimportosimportbisectimportweakreffromcollectionsimportOrderedDictimportsixfromsiximportstring_typesfromsix.movesimport_threadfrom._commonimporttzname_in_python2,_tzinfofrom._commonimporttzrangebase,enfoldfrom._commonimport_validate_fromutc_inputsfrom._factoriesimport_TzSingleton,_TzOffsetFactoryfrom._factoriesimport_TzStrFactorytry:from.winimporttzwin,tzwinlocalexceptImportError:tzwin=tzwinlocal=None# For warning about rounding tzinfofromwarningsimportwarnZERO=datetime.timedelta(0)EPOCH=datetime.datetime(1970,1,1,0,0)EPOCHORDINAL=EPOCH.toordinal()[docs]@six.add_metaclass(_TzSingleton)classtzutc(datetime.tzinfo):""" This is a tzinfo object that represents the UTC time zone. **Examples:** .. doctest:: >>> from datetime import * >>> from dateutil.tz import * >>> datetime.now() datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) >>> datetime.now(tzutc()) datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) >>> datetime.now(tzutc()).tzname() 'UTC' .. versionchanged:: 2.7.0 ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will always return the same object. .. doctest:: >>> from dateutil.tz import tzutc, UTC >>> tzutc() is tzutc() True >>> tzutc() is UTC True """defutcoffset(self,dt):returnZEROdefdst(self,dt):returnZERO@tzname_in_python2deftzname(self,dt):return"UTC"defis_ambiguous(self,dt):""" Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """returnFalse@_validate_fromutc_inputsdeffromutc(self,dt):""" Fast track version of fromutc() returns the original ``dt`` object for any valid :py:class:`datetime.datetime` object. """returndtdef__eq__(self,other):ifnotisinstance(other,(tzutc,tzoffset)):returnNotImplementedreturn(isinstance(other,tzutc)or(isinstance(other,tzoffset)andother._offset==ZERO))__hash__=Nonedef__ne__(self,other):returnnot(self==other)def__repr__(self):return"%s()"%self.__class__.__name____reduce__=object.__reduce__ #: Convenience constant providing a :class:`tzutc()` instance#:#: .. versionadded:: 2.7.0UTC=tzutc()[docs]@six.add_metaclass(_TzOffsetFactory)classtzoffset(datetime.tzinfo):""" A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represented as a :py:class:`datetime.timedelta` object). """def__init__(self,name,offset):self._name=nametry:# Allow a timedeltaoffset=offset.total_seconds()except(TypeError,AttributeError):passself._offset=datetime.timedelta(seconds=_get_supported_offset(offset))defutcoffset(self,dt):returnself._offsetdefdst(self,dt):returnZERO@tzname_in_python2deftzname(self,dt):returnself._name@_validate_fromutc_inputsdeffromutc(self,dt):returndt+self._offsetdefis_ambiguous(self,dt):""" Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """returnFalsedef__eq__(self,other):ifnotisinstance(other,tzoffset):returnNotImplementedreturnself._offset==other._offset__hash__=Nonedef__ne__(self,other):returnnot(self==other)def__repr__(self):return"%s(%s,%s)"%(self.__class__.__name__,repr(self._name),int(self._offset.total_seconds()))__reduce__=object.__reduce__ [docs]classtzlocal(_tzinfo):""" A :class:`tzinfo` subclass built around the ``time`` timezone functions. """def__init__(self):super(tzlocal,self).__init__()self._std_offset=datetime.timedelta(seconds=-time.timezone)iftime.daylight:self._dst_offset=datetime.timedelta(seconds=-time.altzone)else:self._dst_offset=self._std_offsetself._dst_saved=self._dst_offset-self._std_offsetself._hasdst=bool(self._dst_saved)self._tznames=tuple(time.tzname)defutcoffset(self,dt):ifdtisNoneandself._hasdst:returnNoneifself._isdst(dt):returnself._dst_offsetelse:returnself._std_offsetdefdst(self,dt):ifdtisNoneandself._hasdst:returnNoneifself._isdst(dt):returnself._dst_offset-self._std_offsetelse:returnZERO@tzname_in_python2deftzname(self,dt):returnself._tznames[self._isdst(dt)]defis_ambiguous(self,dt):""" Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """naive_dst=self._naive_is_dst(dt)return(notnaive_dstand(naive_dst!=self._naive_is_dst(dt-self._dst_saved)))def_naive_is_dst(self,dt):timestamp=_datetime_to_timestamp(dt)returntime.localtime(timestamp+time.timezone).tm_isdstdef_isdst(self,dt,fold_naive=True):# We can't use mktime here. It is unstable when deciding if# the hour near to a change is DST or not.## timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,# dt.minute, dt.second, dt.weekday(), 0, -1))# return time.localtime(timestamp).tm_isdst## The code above yields the following result:## >>> import tz, datetime# >>> t = tz.tzlocal()# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()# 'BRDT'# >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()# 'BRST'# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()# 'BRST'# >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()# 'BRDT'# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()# 'BRDT'## Here is a more stable implementation:#ifnotself._hasdst:returnFalse# Check for ambiguous times:dstval=self._naive_is_dst(dt)fold=getattr(dt,'fold',None)ifself.is_ambiguous(dt):iffoldisnotNone:returnnotself._fold(dt)else:returnTruereturndstvaldef__eq__(self,other):ifisinstance(other,tzlocal):return(self._std_offset==other._std_offsetandself._dst_offset==other._dst_offset)elifisinstance(other,tzutc):return(notself._hasdstandself._tznames[0]in{'UTC','GMT'}andself._std_offset==ZERO)elifisinstance(other,tzoffset):return(notself._hasdstandself._tznames[0]==other._nameandself._std_offset==other._offset)else:returnNotImplemented__hash__=Nonedef__ne__(self,other):returnnot(self==other)def__repr__(self):return"%s()"%self.__class__.__name____reduce__=object.__reduce__ class_ttinfo(object):__slots__=["offset","delta","isdst","abbr","isstd","isgmt","dstoffset"]def__init__(self):forattrinself.__slots__:setattr(self,attr,None)def__repr__(self):l=[]forattrinself.__slots__:value=getattr(self,attr)ifvalueisnotNone:l.append("%s=%s"%(attr,repr(value)))return"%s(%s)"%(self.__class__.__name__,", ".join(l))def__eq__(self,other):ifnotisinstance(other,_ttinfo):returnNotImplementedreturn(self.offset==other.offsetandself.delta==other.deltaandself.isdst==other.isdstandself.abbr==other.abbrandself.isstd==other.isstdandself.isgmt==other.isgmtandself.dstoffset==other.dstoffset)__hash__=Nonedef__ne__(self,other):returnnot(self==other)def__getstate__(self):state={}fornameinself.__slots__:state[name]=getattr(self,name,None)returnstatedef__setstate__(self,state):fornameinself.__slots__:ifnameinstate:setattr(self,name,state[name])class_tzfile(object):""" Lightweight class for holding the relevant transition and time zone information read from binary tzfiles. """attrs=['trans_list','trans_list_utc','trans_idx','ttinfo_list','ttinfo_std','ttinfo_dst','ttinfo_before','ttinfo_first']def__init__(self,**kwargs):forattrinself.attrs:setattr(self,attr,kwargs.get(attr,None))classtzfile(_tzinfo):""" This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` format timezone files to extract current and historical zone information. :param fileobj: This can be an opened file stream or a file name that the time zone information can be read from. :param filename: This is an optional parameter specifying the source of the time zone information in the event that ``fileobj`` is a file object. If omitted and ``fileobj`` is a file stream, this parameter will be set either to ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. See `Sources for Time Zone and Daylight Saving Time Data <https://data.iana.org/time-zones/tz-link.html>`_ for more information. Time zone files can be compiled from the `IANA Time Zone database files <https://www.iana.org/time-zones>`_ with the `zic time zone compiler <https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_ .. note:: Only construct a ``tzfile`` directly if you have a specific timezone file on disk that you want to read into a Python ``tzinfo`` object. If you want to get a ``tzfile`` representing a specific IANA zone, (e.g. ``'America/New_York'``), you should call :func:`dateutil.tz.gettz` with the zone identifier. **Examples:** Using the US Eastern time zone as an example, we can see that a ``tzfile`` provides time zone information for the standard Daylight Saving offsets: .. testsetup:: tzfile from dateutil.tz import gettz from datetime import datetime .. doctest:: tzfile >>> NYC = gettz('America/New_York') >>> NYC tzfile('/usr/share/zoneinfo/America/New_York') >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST 2016-01-03 00:00:00-05:00 >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT 2016-07-07 00:00:00-04:00 The ``tzfile`` structure contains a fully history of the time zone, so historical dates will also have the right offsets. For example, before the adoption of the UTC standards, New York used local solar mean time: .. doctest:: tzfile >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT 1901-04-12 00:00:00-04:56 And during World War II, New York was on "Eastern War Time", which was a state of permanent daylight saving time: .. doctest:: tzfile >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT 1944-02-07 00:00:00-04:00 """def__init__(self,fileobj,filename=None):super(tzfile,self).__init__()file_opened_here=Falseifisinstance(fileobj,string_types):self._filename=fileobjfileobj=open(fileobj,'rb')file_opened_here=TrueeliffilenameisnotNone:self._filename=filenameelifhasattr(fileobj,"name"):self._filename=fileobj.nameelse:self._filename=repr(fileobj)iffileobjisnotNone:ifnotfile_opened_here:fileobj=_nullcontext(fileobj)withfileobjasfile_stream:tzobj=self._read_tzfile(file_stream)self._set_tzdata(tzobj)def_set_tzdata(self,tzobj):""" Set the time zone data of this object from a _tzfile object """# Copy the relevant attributes over as private attributesforattrin_tzfile.attrs:setattr(self,'_'+attr,getattr(tzobj,attr))def_read_tzfile(self,fileobj):out=_tzfile()# From tzfile(5):## The time zone information files used by tzset(3)# begin with the magic characters "TZif" to identify# them as time zone information files, followed by# sixteen bytes reserved for future use, followed by# six four-byte values of type long, written in a# ``standard'' byte order (the high-order byte# of the value is written first).iffileobj.read(4).decode()!="TZif":raiseValueError("magic not found")fileobj.read(16)(# The number of UTC/local indicators stored in the file.ttisgmtcnt,# The number of standard/wall indicators stored in the file.ttisstdcnt,# The number of leap seconds for which data is# stored in the file.leapcnt,# The number of "transition times" for which data# is stored in the file.timecnt,# The number of "local time types" for which data# is stored in the file (must not be zero).typecnt,# The number of characters of "time zone# abbreviation strings" stored in the file.charcnt,)=struct.unpack(">6l",fileobj.read(24))# The above header is followed by tzh_timecnt four-byte# values of type long, sorted in ascending order.# These values are written in ``standard'' byte order.# Each is used as a transition time (as returned by# time(2)) at which the rules for computing local time# change.iftimecnt:out.trans_list_utc=list(struct.unpack(">%dl"%timecnt,fileobj.read(timecnt*4)))else:out.trans_list_utc=[]# Next come tzh_timecnt one-byte values of type unsigned# char; each one tells which of the different types of# ``local time'' types described in the file is associated# with the same-indexed transition time. These values# serve as indices into an array of ttinfo structures that# appears next in the file.iftimecnt:out.trans_idx=struct.unpack(">%dB"%timecnt,fileobj.read(timecnt))else:out.trans_idx=[]# Each ttinfo structure is written as a four-byte value# for tt_gmtoff of type long, in a standard byte# order, followed by a one-byte value for tt_isdst# and a one-byte value for tt_abbrind. In each# structure, tt_gmtoff gives the number of# seconds to be added to UTC, tt_isdst tells whether# tm_isdst should be set by localtime(3), and# tt_abbrind serves as an index into the array of# time zone abbreviation characters that follow the# ttinfo structure(s) in the file.ttinfo=[]foriinrange(typecnt):ttinfo.append(struct.unpack(">lbb",fileobj.read(6)))abbr=fileobj.read(charcnt).decode()# Then there are tzh_leapcnt pairs of four-byte# values, written in standard byte order; the# first value of each pair gives the time (as# returned by time(2)) at which a leap second# occurs; the second gives the total number of# leap seconds to be applied after the given time.# The pairs of values are sorted in ascending order# by time.# Not used, for now (but seek for correct file position)ifleapcnt:fileobj.seek(leapcnt*8,os.SEEK_CUR)# Then there are tzh_ttisstdcnt standard/wall# indicators, each stored as a one-byte value;# they tell whether the transition times associated# with local time types were specified as standard# time or wall clock time, and are used when# a time zone file is used in handling POSIX-style# time zone environment variables.ifttisstdcnt:isstd=struct.unpack(">%db"%ttisstdcnt,fileobj.read(ttisstdcnt))# Finally, there are tzh_ttisgmtcnt UTC/local# indicators, each stored as a one-byte value;# they tell whether the transition times associated# with local time types were specified as UTC or# local time, and are used when a time zone file# is used in handling POSIX-style time zone envi-# ronment variables.ifttisgmtcnt:isgmt=struct.unpack(">%db"%ttisgmtcnt,fileobj.read(ttisgmtcnt))# Build ttinfo listout.ttinfo_list=[]foriinrange(typecnt):gmtoff,isdst,abbrind=ttinfo[i]gmtoff=_get_supported_offset(gmtoff)tti=_ttinfo()tti.offset=gmtofftti.dstoffset=datetime.timedelta(0)tti.delta=datetime.timedelta(seconds=gmtoff)tti.isdst=isdsttti.abbr=abbr[abbrind:abbr.find('\x00',abbrind)]tti.isstd=(ttisstdcnt>iandisstd[i]!=0)tti.isgmt=(ttisgmtcnt>iandisgmt[i]!=0)out.ttinfo_list.append(tti)# Replace ttinfo indexes for ttinfo objects.out.trans_idx=[out.ttinfo_list[idx]foridxinout.trans_idx]# Set standard, dst, and before ttinfos. before will be# used when a given time is before any transitions,# and will be set to the first non-dst ttinfo, or to# the first dst, if all of them are dst.out.ttinfo_std=Noneout.ttinfo_dst=Noneout.ttinfo_before=Noneifout.ttinfo_list:ifnotout.trans_list_utc:out.ttinfo_std=out.ttinfo_first=out.ttinfo_list[0]else:foriinrange(timecnt-1,-1,-1):tti=out.trans_idx[i]ifnotout.ttinfo_stdandnottti.isdst:out.ttinfo_std=ttielifnotout.ttinfo_dstandtti.isdst:out.ttinfo_dst=ttiifout.ttinfo_stdandout.ttinfo_dst:breakelse:ifout.ttinfo_dstandnotout.ttinfo_std:out.ttinfo_std=out.ttinfo_dstforttiinout.ttinfo_list:ifnottti.isdst:out.ttinfo_before=ttibreakelse:out.ttinfo_before=out.ttinfo_list[0]# Now fix transition times to become relative to wall time.## I'm not sure about this. In my tests, the tz source file# is setup to wall time, and in the binary file isstd and# isgmt are off, so it should be in wall time. OTOH, it's# always in gmt time. Let me know if you have comments# about this.lastdst=Nonelastoffset=Nonelastdstoffset=Nonelastbaseoffset=Noneout.trans_list=[]fori,ttiinenumerate(out.trans_idx):offset=tti.offsetdstoffset=0iflastdstisnotNone:iftti.isdst:ifnotlastdst:dstoffset=offset-lastoffsetifnotdstoffsetandlastdstoffset:dstoffset=lastdstoffsettti.dstoffset=datetime.timedelta(seconds=dstoffset)lastdstoffset=dstoffset# If a time zone changes its base offset during a DST transition,# then you need to adjust by the previous base offset to get the# transition time in local time. Otherwise you use the current# base offset. Ideally, I would have some mathematical proof of# why this is true, but I haven't really thought about it enough.baseoffset=offset-dstoffsetadjustment=baseoffsetif(lastbaseoffsetisnotNoneandbaseoffset!=lastbaseoffsetandtti.isdst!=lastdst):# The base DST has changedadjustment=lastbaseoffsetlastdst=tti.isdstlastoffset=offsetlastbaseoffset=baseoffsetout.trans_list.append(out.trans_list_utc[i]+adjustment)out.trans_idx=tuple(out.trans_idx)out.trans_list=tuple(out.trans_list)out.trans_list_utc=tuple(out.trans_list_utc)returnoutdef_find_last_transition(self,dt,in_utc=False):# If there's no list, there are no transitions to findifnotself._trans_list:returnNonetimestamp=_datetime_to_timestamp(dt)# Find where the timestamp fits in the transition list - if the# timestamp is a transition time, it's part of the "after" period.trans_list=self._trans_list_utcifin_utcelseself._trans_listidx=bisect.bisect_right(trans_list,timestamp)# We want to know when the previous transition was, so subtract off 1returnidx-1def_get_ttinfo(self,idx):# For no list or after the last transition, default to _ttinfo_stdifidxisNoneor(idx+1)>=len(self._trans_list):returnself._ttinfo_std# If there is a list and the time is before it, return _ttinfo_beforeifidx<0:returnself._ttinfo_beforereturnself._trans_idx[idx]def_find_ttinfo(self,dt):idx=self._resolve_ambiguous_time(dt)returnself._get_ttinfo(idx)deffromutc(self,dt):""" The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone. """# These isinstance checks are in datetime.tzinfo, so we'll preserve# them, even if we don't care about duck typing.ifnotisinstance(dt,datetime.datetime):raiseTypeError("fromutc() requires a datetime argument")ifdt.tzinfoisnotself:raiseValueError("dt.tzinfo is not self")# First treat UTC as wall time and get the transition we're in.idx=self._find_last_transition(dt,in_utc=True)tti=self._get_ttinfo(idx)dt_out=dt+datetime.timedelta(seconds=tti.offset)fold=self.is_ambiguous(dt_out,idx=idx)returnenfold(dt_out,fold=int(fold))defis_ambiguous(self,dt,idx=None):""" Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ifidxisNone:idx=self._find_last_transition(dt)# Calculate the difference in offsets from current to previoustimestamp=_datetime_to_timestamp(dt)tti=self._get_ttinfo(idx)ifidxisNoneoridx<=0:returnFalseod=self._get_ttinfo(idx-1).offset-tti.offsettt=self._trans_list[idx]# Transition timereturntimestamp<tt+oddef_resolve_ambiguous_time(self,dt):idx=self._find_last_transition(dt)# If we have no transitions, return the index_fold=self._fold(dt)ifidxisNoneoridx==0:returnidx# If it's ambiguous and we're in a fold, shift to a different index.idx_offset=int(not_foldandself.is_ambiguous(dt,idx))returnidx-idx_offsetdefutcoffset(self,dt):ifdtisNone:returnNoneifnotself._ttinfo_std:returnZEROreturnself._find_ttinfo(dt).deltadefdst(self,dt):ifdtisNone:returnNoneifnotself._ttinfo_dst:returnZEROtti=self._find_ttinfo(dt)ifnottti.isdst:returnZERO# The documentation says that utcoffset()-dst() must# be constant for every dt.returntti.dstoffset@tzname_in_python2deftzname(self,dt):ifnotself._ttinfo_stdordtisNone:returnNonereturnself._find_ttinfo(dt).abbrdef__eq__(self,other):ifnotisinstance(other,tzfile):returnNotImplementedreturn(self._trans_list==other._trans_listandself._trans_idx==other._trans_idxandself._ttinfo_list==other._ttinfo_list)__hash__=Nonedef__ne__(self,other):returnnot(self==other)def__repr__(self):return"%s(%s)"%(self.__class__.__name__,repr(self._filename))def__reduce__(self):returnself.__reduce_ex__(None)def__reduce_ex__(self,protocol):return(self.__class__,(None,self._filename),self.__dict__)[docs]classtzrange(tzrangebase):""" The ``tzrange`` object is a time zone specified by a set of offsets and abbreviations, equivalent to the way the ``TZ`` variable can be specified in POSIX-like systems, but using Python delta objects to specify DST start, end and offsets. :param stdabbr: The abbreviation for standard time (e.g. ``'EST'``). :param stdoffset: An integer or :class:`datetime.timedelta` object or equivalent specifying the base offset from UTC. If unspecified, +00:00 is used. :param dstabbr: The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). If specified, with no other DST information, DST is assumed to occur and the default behavior or ``dstoffset``, ``start`` and ``end`` is used. If unspecified and no other DST information is specified, it is assumed that this zone has no DST. If this is unspecified and other DST information is *is* specified, DST occurs in the zone but the time zone abbreviation is left unchanged. :param dstoffset: A an integer or :class:`datetime.timedelta` object or equivalent specifying the UTC offset during DST. If unspecified and any other DST information is specified, it is assumed to be the STD offset +1 hour. :param start: A :class:`relativedelta.relativedelta` object or equivalent specifying the time and time of year that daylight savings time starts. To specify, for example, that DST starts at 2AM on the 2nd Sunday in March, pass: ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` If unspecified and any other DST information is specified, the default value is 2 AM on the first Sunday in April. :param end: A :class:`relativedelta.relativedelta` object or equivalent representing the time and time of year that daylight savings time ends, with the same specification method as in ``start``. One note is that this should point to the first time in the *standard* zone, so if a transition occurs at 2AM in the DST zone and the clocks are set back 1 hour to 1AM, set the ``hours`` parameter to +1. **Examples:** .. testsetup:: tzrange from dateutil.tz import tzrange, tzstr .. doctest:: tzrange >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") True >>> from dateutil.relativedelta import * >>> range1 = tzrange("EST", -18000, "EDT") >>> range2 = tzrange("EST", -18000, "EDT", -14400, ... relativedelta(hours=+2, month=4, day=1, ... weekday=SU(+1)), ... relativedelta(hours=+1, month=10, day=31, ... weekday=SU(-1))) >>> tzstr('EST5EDT') == range1 == range2 True """def__init__(self,stdabbr,stdoffset=None,dstabbr=None,dstoffset=None,start=None,end=None):globalrelativedeltafromdateutilimportrelativedeltaself._std_abbr=stdabbrself._dst_abbr=dstabbrtry:stdoffset=stdoffset.total_seconds()except(TypeError,AttributeError):passtry:dstoffset=dstoffset.total_seconds()except(TypeError,AttributeError):passifstdoffsetisnotNone:self._std_offset=datetime.timedelta(seconds=stdoffset)else:self._std_offset=ZEROifdstoffsetisnotNone:self._dst_offset=datetime.timedelta(seconds=dstoffset)elifdstabbrandstdoffsetisnotNone:self._dst_offset=self._std_offset+datetime.timedelta(hours=+1)else:self._dst_offset=ZEROifdstabbrandstartisNone:self._start_delta=relativedelta.relativedelta(hours=+2,month=4,day=1,weekday=relativedelta.SU(+1))else:self._start_delta=startifdstabbrandendisNone:self._end_delta=relativedelta.relativedelta(hours=+1,month=10,day=31,weekday=relativedelta.SU(-1))else:self._end_delta=endself._dst_base_offset_=self._dst_offset-self._std_offsetself.hasdst=bool(self._start_delta)deftransitions(self,year):""" For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ifnotself.hasdst:returnNonebase_year=datetime.datetime(year,1,1)start=base_year+self._start_deltaend=base_year+self._end_deltareturn(start,end)def__eq__(self,other):ifnotisinstance(other,tzrange):returnNotImplementedreturn(self._std_abbr==other._std_abbrandself._dst_abbr==other._dst_abbrandself._std_offset==other._std_offsetandself._dst_offset==other._dst_offsetandself._start_delta==other._start_deltaandself._end_delta==other._end_delta)@propertydef_dst_base_offset(self):returnself._dst_base_offset_ [docs]@six.add_metaclass(_TzStrFactory)classtzstr(tzrange):""" ``tzstr`` objects are time zone objects specified by a time-zone string as it would be passed to a ``TZ`` variable on POSIX-style systems (see the `GNU C Library: TZ Variable`_ for more details). There is one notable exception, which is that POSIX-style time zones use an inverted offset format, so normally ``GMT+3`` would be parsed as an offset 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX behavior, pass a ``True`` value to ``posix_offset``. The :class:`tzrange` object provides the same functionality, but is specified using :class:`relativedelta.relativedelta` objects. rather than strings. :param s: A time zone string in ``TZ`` variable format. This can be a :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: :class:`unicode`) or a stream emitting unicode characters (e.g. :class:`StringIO`). :param posix_offset: Optional. If set to ``True``, interpret strings such as ``GMT+3`` or ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the POSIX standard. .. caution:: Prior to version 2.7.0, this function also supported time zones in the format: * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` This format is non-standard and has been deprecated; this function will raise a :class:`DeprecatedTZFormatWarning` until support is removed in a future version. .. _`GNU C Library: TZ Variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html """def__init__(self,s,posix_offset=False):globalparserfromdateutil.parserimport_parserasparserself._s=sres=parser._parsetz(s)ifresisNoneorres.any_unused_tokens:raiseValueError("unknown string format")# Here we break the compatibility with the TZ variable handling.# GMT-3 actually *means* the timezone -3.ifres.stdabbrin("GMT","UTC")andnotposix_offset:res.stdoffset*=-1# We must initialize it first, since _delta() needs# _std_offset and _dst_offset set. Use False in start/end# to avoid building it two times.tzrange.__init__(self,res.stdabbr,res.stdoffset,res.dstabbr,res.dstoffset,start=False,end=False)ifnotres.dstabbr:self._start_delta=Noneself._end_delta=Noneelse:self._start_delta=self._delta(res.start)ifself._start_delta:self._end_delta=self._delta(res.end,isend=1)self.hasdst=bool(self._start_delta)def_delta(self,x,isend=0):fromdateutilimportrelativedeltakwargs={}ifx.monthisnotNone:kwargs["month"]=x.monthifx.weekdayisnotNone:kwargs["weekday"]=relativedelta.weekday(x.weekday,x.week)ifx.week>0:kwargs["day"]=1else:kwargs["day"]=31elifx.day:kwargs["day"]=x.dayelifx.ydayisnotNone:kwargs["yearday"]=x.ydayelifx.jydayisnotNone:kwargs["nlyearday"]=x.jydayifnotkwargs:# Default is to start on first sunday of april, and end# on last sunday of october.ifnotisend:kwargs["month"]=4kwargs["day"]=1kwargs["weekday"]=relativedelta.SU(+1)else:kwargs["month"]=10kwargs["day"]=31kwargs["weekday"]=relativedelta.SU(-1)ifx.timeisnotNone:kwargs["seconds"]=x.timeelse:# Default is 2AM.kwargs["seconds"]=7200ifisend:# Convert to standard time, to follow the documented way# of working with the extra hour. See the documentation# of the tzinfo class.delta=self._dst_offset-self._std_offsetkwargs["seconds"]-=delta.seconds+delta.days*86400returnrelativedelta.relativedelta(**kwargs)def__repr__(self):return"%s(%s)"%(self.__class__.__name__,repr(self._s)) class_tzicalvtzcomp(object):def__init__(self,tzoffsetfrom,tzoffsetto,isdst,tzname=None,rrule=None):self.tzoffsetfrom=datetime.timedelta(seconds=tzoffsetfrom)self.tzoffsetto=datetime.timedelta(seconds=tzoffsetto)self.tzoffsetdiff=self.tzoffsetto-self.tzoffsetfromself.isdst=isdstself.tzname=tznameself.rrule=rruleclass_tzicalvtz(_tzinfo):def__init__(self,tzid,comps=[]):super(_tzicalvtz,self).__init__()self._tzid=tzidself._comps=compsself._cachedate=[]self._cachecomp=[]self._cache_lock=_thread.allocate_lock()def_find_comp(self,dt):iflen(self._comps)==1:returnself._comps[0]dt=dt.replace(tzinfo=None)try:withself._cache_lock:returnself._cachecomp[self._cachedate.index((dt,self._fold(dt)))]exceptValueError:passlastcompdt=Nonelastcomp=Noneforcompinself._comps:compdt=self._find_compdt(comp,dt)ifcompdtand(notlastcompdtorlastcompdt<compdt):lastcompdt=compdtlastcomp=compifnotlastcomp:# RFC says nothing about what to do when a given# time is before the first onset date. We'll look for the# first standard component, or the first component, if# none is found.forcompinself._comps:ifnotcomp.isdst:lastcomp=compbreakelse:lastcomp=comp[0]withself._cache_lock:self._cachedate.insert(0,(dt,self._fold(dt)))self._cachecomp.insert(0,lastcomp)iflen(self._cachedate)>10:self._cachedate.pop()self._cachecomp.pop()returnlastcompdef_find_compdt(self,comp,dt):ifcomp.tzoffsetdiff<ZEROandself._fold(dt):dt-=comp.tzoffsetdiffcompdt=comp.rrule.before(dt,inc=True)returncompdtdefutcoffset(self,dt):ifdtisNone:returnNonereturnself._find_comp(dt).tzoffsettodefdst(self,dt):comp=self._find_comp(dt)ifcomp.isdst:returncomp.tzoffsetdiffelse:returnZERO@tzname_in_python2deftzname(self,dt):returnself._find_comp(dt).tznamedef__repr__(self):return"<tzicalvtz%s>"%repr(self._tzid)__reduce__=object.__reduce__[docs]classtzical(object):""" This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. :param `fileobj`: A file or stream in iCalendar format, which should be UTF-8 encoded with CRLF endings. .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 """def__init__(self,fileobj):globalrrulefromdateutilimportrruleifisinstance(fileobj,string_types):self._s=fileobj# ical should be encoded in UTF-8 with CRLFfileobj=open(fileobj,'r')else:self._s=getattr(fileobj,'name',repr(fileobj))fileobj=_nullcontext(fileobj)self._vtz={}withfileobjasfobj:self._parse_rfc(fobj.read())[docs]defkeys(self):""" Retrieves the available time zones as a list. """returnlist(self._vtz.keys()) [docs]defget(self,tzid=None):""" Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. :param tzid: If there is exactly one time zone available, omitting ``tzid`` or passing :py:const:`None` value returns it. Otherwise a valid key (which can be retrieved from :func:`keys`) is required. :raises ValueError: Raised if ``tzid`` is not specified but there are either more or fewer than 1 zone defined. :returns: Returns either a :py:class:`datetime.tzinfo` object representing the relevant time zone or :py:const:`None` if the ``tzid`` was not found. """iftzidisNone:iflen(self._vtz)==0:raiseValueError("no timezones defined")eliflen(self._vtz)>1:raiseValueError("more than one timezone available")tzid=next(iter(self._vtz))returnself._vtz.get(tzid) def_parse_offset(self,s):s=s.strip()ifnots:raiseValueError("empty offset")ifs[0]in('+','-'):signal=(-1,+1)[s[0]=='+']s=s[1:]else:signal=+1iflen(s)==4:return(int(s[:2])*3600+int(s[2:])*60)*signaleliflen(s)==6:return(int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signalelse:raiseValueError("invalid offset: "+s)def_parse_rfc(self,s):lines=s.splitlines()ifnotlines:raiseValueError("empty string")# Unfoldi=0whilei<len(lines):line=lines[i].rstrip()ifnotline:dellines[i]elifi>0andline[0]==" ":lines[i-1]+=line[1:]dellines[i]else:i+=1tzid=Nonecomps=[]invtz=Falsecomptype=Noneforlineinlines:ifnotline:continuename,value=line.split(':',1)parms=name.split(';')ifnotparms:raiseValueError("empty property name")name=parms[0].upper()parms=parms[1:]ifinvtz:ifname=="BEGIN":ifvaluein("STANDARD","DAYLIGHT"):# Process componentpasselse:raiseValueError("unknown component: "+value)comptype=valuefounddtstart=Falsetzoffsetfrom=Nonetzoffsetto=Nonerrulelines=[]tzname=Noneelifname=="END":ifvalue=="VTIMEZONE":ifcomptype:raiseValueError("component not closed: "+comptype)ifnottzid:raiseValueError("mandatory TZID not found")ifnotcomps:raiseValueError("at least one component is needed")# Process vtimezoneself._vtz[tzid]=_tzicalvtz(tzid,comps)invtz=Falseelifvalue==comptype:ifnotfounddtstart:raiseValueError("mandatory DTSTART not found")iftzoffsetfromisNone:raiseValueError("mandatory TZOFFSETFROM not found")iftzoffsettoisNone:raiseValueError("mandatory TZOFFSETFROM not found")# Process componentrr=Noneifrrulelines:rr=rrule.rrulestr("\n".join(rrulelines),compatible=True,ignoretz=True,cache=True)comp=_tzicalvtzcomp(tzoffsetfrom,tzoffsetto,(comptype=="DAYLIGHT"),tzname,rr)comps.append(comp)comptype=Noneelse:raiseValueError("invalid component end: "+value)elifcomptype:ifname=="DTSTART":# DTSTART in VTIMEZONE takes a subset of valid RRULE# values under RFC 5545.forparminparms:ifparm!='VALUE=DATE-TIME':msg=('Unsupported DTSTART param in '+'VTIMEZONE: '+parm)raiseValueError(msg)rrulelines.append(line)founddtstart=Trueelifnamein("RRULE","RDATE","EXRULE","EXDATE"):rrulelines.append(line)elifname=="TZOFFSETFROM":ifparms:raiseValueError("unsupported%s parm:%s "%(name,parms[0]))tzoffsetfrom=self._parse_offset(value)elifname=="TZOFFSETTO":ifparms:raiseValueError("unsupported TZOFFSETTO parm: "+parms[0])tzoffsetto=self._parse_offset(value)elifname=="TZNAME":ifparms:raiseValueError("unsupported TZNAME parm: "+parms[0])tzname=valueelifname=="COMMENT":passelse:raiseValueError("unsupported property: "+name)else:ifname=="TZID":ifparms:raiseValueError("unsupported TZID parm: "+parms[0])tzid=valueelifnamein("TZURL","LAST-MODIFIED","COMMENT"):passelse:raiseValueError("unsupported property: "+name)elifname=="BEGIN"andvalue=="VTIMEZONE":tzid=Nonecomps=[]invtz=Truedef__repr__(self):return"%s(%s)"%(self.__class__.__name__,repr(self._s)) ifsys.platform!="win32":TZFILES=["/etc/localtime","localtime"]TZPATHS=["/usr/share/zoneinfo","/usr/lib/zoneinfo","/usr/share/lib/zoneinfo","/etc/zoneinfo"]else:TZFILES=[]TZPATHS=[]def__get_gettz():tzlocal_classes=(tzlocal,)iftzwinlocalisnotNone:tzlocal_classes+=(tzwinlocal,)classGettzFunc(object):""" Retrieve a time zone object from a string representation This function is intended to retrieve the :py:class:`tzinfo` subclass that best represents the time zone that would be used if a POSIX `TZ variable`_ were set to the same value. If no argument or an empty string is passed to ``gettz``, local time is returned: .. code-block:: python3 >>> gettz() tzfile('/etc/localtime') This function is also the preferred way to map IANA tz database keys to :class:`tzfile` objects: .. code-block:: python3 >>> gettz('Pacific/Kiritimati') tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') On Windows, the standard is extended to include the Windows-specific zone names provided by the operating system: .. code-block:: python3 >>> gettz('Egypt Standard Time') tzwin('Egypt Standard Time') Passing a GNU ``TZ`` style string time zone specification returns a :class:`tzstr` object: .. code-block:: python3 >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') :param name: A time zone name (IANA, or, on Windows, Windows keys), location of a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone specifier. An empty string, no argument or ``None`` is interpreted as local time. :return: Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` subclasses. .. versionchanged:: 2.7.0 After version 2.7.0, any two calls to ``gettz`` using the same input strings will return the same object: .. code-block:: python3 >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') True In addition to improving performance, this ensures that `"same zone" semantics`_ are used for datetimes in the same zone. .. _`TZ variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html .. _`"same zone" semantics`: https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html """def__init__(self):self.__instances=weakref.WeakValueDictionary()self.__strong_cache_size=8self.__strong_cache=OrderedDict()self._cache_lock=_thread.allocate_lock()def__call__(self,name=None):withself._cache_lock:rv=self.__instances.get(name,None)ifrvisNone:rv=self.nocache(name=name)ifnot(nameisNoneorisinstance(rv,tzlocal_classes)orrvisNone):# tzlocal is slightly more complicated than the other# time zone providers because it depends on environment# at construction time, so don't cache that.## We also cannot store weak references to None, so we# will also not store that.self.__instances[name]=rvelse:# No need for strong caching, return immediatelyreturnrvself.__strong_cache[name]=self.__strong_cache.pop(name,rv)iflen(self.__strong_cache)>self.__strong_cache_size:self.__strong_cache.popitem(last=False)returnrvdefset_cache_size(self,size):withself._cache_lock:self.__strong_cache_size=sizewhilelen(self.__strong_cache)>size:self.__strong_cache.popitem(last=False)defcache_clear(self):withself._cache_lock:self.__instances=weakref.WeakValueDictionary()self.__strong_cache.clear()@staticmethoddefnocache(name=None):"""A non-cached version of gettz"""tz=Noneifnotname:try:name=os.environ["TZ"]exceptKeyError:passifnameisNoneornamein("",":"):forfilepathinTZFILES:ifnotos.path.isabs(filepath):filename=filepathforpathinTZPATHS:filepath=os.path.join(path,filename)ifos.path.isfile(filepath):breakelse:continueifos.path.isfile(filepath):try:tz=tzfile(filepath)breakexcept(IOError,OSError,ValueError):passelse:tz=tzlocal()else:try:ifname.startswith(":"):name=name[1:]exceptTypeErrorase:ifisinstance(name,bytes):new_msg="gettz argument should be str, not bytes"six.raise_from(TypeError(new_msg),e)else:raiseifos.path.isabs(name):ifos.path.isfile(name):tz=tzfile(name)else:tz=Noneelse:forpathinTZPATHS:filepath=os.path.join(path,name)ifnotos.path.isfile(filepath):filepath=filepath.replace(' ','_')ifnotos.path.isfile(filepath):continuetry:tz=tzfile(filepath)breakexcept(IOError,OSError,ValueError):passelse:tz=NoneiftzwinisnotNone:try:tz=tzwin(name)except(WindowsError,UnicodeEncodeError):# UnicodeEncodeError is for Python 2.7 compattz=Noneifnottz:fromdateutil.zoneinfoimportget_zonefile_instancetz=get_zonefile_instance().get(name)ifnottz:forcinname:# name is not a tzstr unless it has at least# one offset. For short values of "name", an# explicit for loop seems to be the fastest way# To determine if a string contains a digitifcin"0123456789":try:tz=tzstr(name)exceptValueError:passbreakelse:ifnamein("GMT","UTC"):tz=UTCelifnameintime.tzname:tz=tzlocal()returntzreturnGettzFunc()gettz=__get_gettz()del__get_gettz[docs]defdatetime_exists(dt,tz=None):""" Given a datetime and a time zone, determine whether or not a given datetime would fall in a gap. :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" exists in ``tz``. .. versionadded:: 2.7.0 """iftzisNone:ifdt.tzinfoisNone:raiseValueError('Datetime is naive and no time zone provided.')tz=dt.tzinfodt=dt.replace(tzinfo=None)# This is essentially a test of whether or not the datetime can survive# a round trip to UTC.dt_rt=dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz)dt_rt=dt_rt.replace(tzinfo=None)returndt==dt_rt [docs]defdatetime_ambiguous(dt,tz=None):""" Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" is ambiguous in ``tz``. .. versionadded:: 2.6.0 """iftzisNone:ifdt.tzinfoisNone:raiseValueError('Datetime is naive and no time zone provided.')tz=dt.tzinfo# If a time zone defines its own "is_ambiguous" function, we'll use that.is_ambiguous_fn=getattr(tz,'is_ambiguous',None)ifis_ambiguous_fnisnotNone:try:returntz.is_ambiguous(dt)exceptException:pass# If it doesn't come out and tell us it's ambiguous, we'll just check if# the fold attribute has any effect on this particular date and time.dt=dt.replace(tzinfo=tz)wall_0=enfold(dt,fold=0)wall_1=enfold(dt,fold=1)same_offset=wall_0.utcoffset()==wall_1.utcoffset()same_dst=wall_0.dst()==wall_1.dst()returnnot(same_offsetandsame_dst) [docs]defresolve_imaginary(dt):""" Given a datetime that may be imaginary, return an existing datetime. This function assumes that an imaginary datetime represents what the wall time would be in a zone had the offset transition not occurred, so it will always fall forward by the transition's change in offset. .. doctest:: >>> from dateutil import tz >>> from datetime import datetime >>> NYC = tz.gettz('America/New_York') >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) 2017-03-12 03:30:00-04:00 >>> KIR = tz.gettz('Pacific/Kiritimati') >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) 1995-01-02 12:30:00+14:00 As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, existing datetime, so a round-trip to and from UTC is sufficient to get an extant datetime, however, this generally "falls back" to an earlier time rather than falling forward to the STD side (though no guarantees are made about this behavior). :param dt: A :class:`datetime.datetime` which may or may not exist. :return: Returns an existing :class:`datetime.datetime`. If ``dt`` was not imaginary, the datetime returned is guaranteed to be the same object passed to the function. .. versionadded:: 2.7.0 """ifdt.tzinfoisnotNoneandnotdatetime_exists(dt):curr_offset=(dt+datetime.timedelta(hours=24)).utcoffset()old_offset=(dt-datetime.timedelta(hours=24)).utcoffset()dt+=curr_offset-old_offsetreturndt def_datetime_to_timestamp(dt):""" Convert a :class:`datetime.datetime` object to an epoch timestamp in seconds since January 1, 1970, ignoring the time zone. """return(dt.replace(tzinfo=None)-EPOCH).total_seconds()ifsys.version_info>=(3,6):def_get_supported_offset(second_offset):returnsecond_offsetelse:def_get_supported_offset(second_offset):# For python pre-3.6, round to full-minutes if that's not the case.# Python's datetime doesn't accept sub-minute timezones. Check# http://python.org/sf/1447945 or https://bugs.python.org/issue5288# for some information.old_offset=second_offsetcalculated_offset=60*((second_offset+30)//60)returncalculated_offsettry:# Python 3.7 featurefromcontextlibimportnullcontextas_nullcontextexceptImportError:class_nullcontext(object):""" Class for wrapping contexts so that they are passed through in a with statement. """def__init__(self,context):self.context=contextdef__enter__(self):returnself.contextdef__exit__(*args,**kwargs):pass# vim:ts=4:sw=4:et