Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 500 – A protocol for delegating datetime methods to their tzinfo implementations

PEP 500 – A protocol for delegating datetime methods to their tzinfo implementations

Author:
Alexander Belopolsky <alexander.belopolsky at gmail.com>, Tim Peters <tim.peters at gmail.com>
Discussions-To:
Datetime-SIG list
Status:
Rejected
Type:
Standards Track
Requires:
495
Created:
08-Aug-2015
Resolution:
Datetime-SIG message

Table of Contents

Abstract

This PEP specifies a new protocol (PDDM - “A Protocol for DelegatingDatetime Methods”) that can be used by concrete implementations of thedatetime.tzinfo interface to override aware datetime arithmetics,formatting and parsing. We describe changes to thedatetime.datetime class to support the new protocol and propose anew abstract classdatetime.tzstrict that implements parts of thisprotocol necessary to make aware datetime instances to follow “strict”arithmetic rules.

Rationale

As of Python 3.5, aware datetime instances that share atzinfoobject follow the rules of arithmetics that are induced by a simplebijection between (year, month, day, hour, minute, second,microsecond) 7-tuples and large integers. In this arithmetics, thedifference between YEAR-11-02T12:00 and YEAR-11-01T12:00 is always 24hours, even though in the US/Eastern timezone, for example, there are25 hours between 2014-11-01T12:00 and 2014-11-02T12:00 because thelocal clocks were rolled back one hour at 2014-11-02T02:00,introducing an extra hour in the night between 2014-11-01 and2014-11-02.

Many business applications require the use of Python’s simplified viewof local dates. No self-respecting car rental company will charge itscustomers more for a week that straddles the end of DST than for anyother week or require that they return the car an hour early.Therefore, changing the current rules for aware datetime arithmeticswill not only create a backward compatibility nightmare, it willeliminate support for legitimate and common use cases.

Since it is impossible to choose universal rules for local timearithmetics, we propose to delegate implementation of those rules tothe classes that implementdatetime.tzinfo interface. With suchdelegation in place, users will be able to choose between differentarithmetics by simply picking instances of different classes for thevalue oftzinfo.

Protocol

Subtraction of datetime

Atzinfo subclass supporting the PDDM, may define a method called__datetime_diff__ that should take twodatetime.datetimeinstances and return adatetime.timedelta instance representingthe time elapsed from the time represented by the first datetimeinstance to another.

Addition

Atzinfo subclass supporting the PDDM, may define a method called__datetime_add__ that should take two arguments–a datetime and atimedelta instances–and return a datetime instance.

Subtraction of timedelta

Atzinfo subclass supporting the PDDM, may define a method called__datetime_sub__ that should take two arguments–a datetime and atimedelta instances–and return a datetime instance.

Formatting

Atzinfo subclass supporting the PDDM, may define methods called__datetime_isoformat__ and__datetime_strftime__.

The__datetime_isoformat__ method should take a datetime instanceand an optional separator and produce a string representation of thegiven datetime instance.

The__datetime_strftime__ method should take a datetime instanceand a format string and produce a string representation of the givendatetime instance formatted according to the given format.

Parsing

Atzinfo subclass supporting the PDDM, may define a class methodcalled__datetime_strptime__ and register the “canonical” names ofthe timezones that it implements with a registry.TODO Describe aregistry.

Changes to datetime methods

Subtraction

classdatetime:def__sub__(self,other):ifisinstance(other,datetime):try:self_diff=self.tzinfo.__datetime_diff__exceptAttributeError:self_diff=Nonetry:other_diff=self.tzinfo.__datetime_diff__exceptAttributeError:other_diff=Noneifself_diffisnotNone:ifself_diffisnotother_diffandself_diff.__func__isnotother_diff.__func__:raiseValueError("Cannot find difference of two datetimes with ""different tzinfo.__datetime_diff__ implementations.")returnself_diff(self,other)elifisinstance(other,timedelta):try:sub=self.tzinfo.__datetime_sub__exceptAttributeError:passelse:returnsub(self,other)returnself+-otherelse:returnNotImplemented# current implementation

Addition

Addition of a timedelta to a datetime instance will be delegated to theself.tzinfo.__datetime_add__ method whenever it is defined.

Strict arithmetics

A new abstract subclass ofdatetime.tzinfo class calleddatetime.tzstrictwill be added to thedatetime module. This subclass will not implement theutcoffset(),tzname() ordst() methods, but will implement some of themethods of the PDDM.

The PDDM methods implemented bytzstrict will be equivalent to the following:

classtzstrict(tzinfo):def__datetime_diff__(self,dt1,dt2):utc_dt1=dt1.astimezone(timezone.utc)utc_dt2=dt2.astimezone(timezone.utc)returnutc_dt2-utc_dt1def__datetime_add__(self,dt,delta):utc_dt=dt.astimezone(timezone.utc)return(utc_dt+delta).astimezone(self)def__datetime_sub__(self,dt,delta):utc_dt=dt.astimezone(timezone.utc)return(utc_dt-delta).astimezone(self)

Parsing and formatting

Datetime methodsstrftime andisoformat will delegate to the namesakemethods of theirtzinfo members whenever those methods are defined.

When thedatetime.strptime method is given a format string thatcontains a%Z instruction, it will lookup thetzinfoimplementation in the registry by the given timezone name and call its__datetime_strptime__ method.

Applications

This PEP will enable third party implementation of many differenttimekeeping schemes including:

  • Julian / Microsoft Excel calendar.
  • “Right” timezones with the leap second support.
  • French revolutionary calendar (with a lot of work).

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0500.rst

Last modified:2025-02-01 08:59:27 GMT


[8]ページ先頭

©2009-2026 Movatter.jp