_datetimemodule.c 227 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140
  1. /* C implementation for the date/time type documented at
  2. * https://www.zope.dev/Members/fdrake/DateTimeWiki/FrontPage
  3. */
  4. /* bpo-35081: Defining this prevents including the C API capsule;
  5. * internal versions of the Py*_Check macros which do not require
  6. * the capsule are defined below */
  7. #define _PY_DATETIME_IMPL
  8. #ifndef Py_BUILD_CORE_BUILTIN
  9. # define Py_BUILD_CORE_MODULE 1
  10. #endif
  11. #include "Python.h"
  12. #include "pycore_long.h" // _PyLong_GetOne()
  13. #include "pycore_object.h" // _PyObject_Init()
  14. #include "datetime.h"
  15. #include "structmember.h" // PyMemberDef
  16. #include <time.h>
  17. #ifdef MS_WINDOWS
  18. # include <winsock2.h> /* struct timeval */
  19. #endif
  20. #define PyDate_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateType)
  21. #define PyDate_CheckExact(op) Py_IS_TYPE(op, &PyDateTime_DateType)
  22. #define PyDateTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateTimeType)
  23. #define PyDateTime_CheckExact(op) Py_IS_TYPE(op, &PyDateTime_DateTimeType)
  24. #define PyTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_TimeType)
  25. #define PyTime_CheckExact(op) Py_IS_TYPE(op, &PyDateTime_TimeType)
  26. #define PyDelta_Check(op) PyObject_TypeCheck(op, &PyDateTime_DeltaType)
  27. #define PyDelta_CheckExact(op) Py_IS_TYPE(op, &PyDateTime_DeltaType)
  28. #define PyTZInfo_Check(op) PyObject_TypeCheck(op, &PyDateTime_TZInfoType)
  29. #define PyTZInfo_CheckExact(op) Py_IS_TYPE(op, &PyDateTime_TZInfoType)
  30. #define PyTimezone_Check(op) PyObject_TypeCheck(op, &PyDateTime_TimeZoneType)
  31. /*[clinic input]
  32. module datetime
  33. class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
  34. class datetime.date "PyDateTime_Date *" "&PyDateTime_DateType"
  35. class datetime.IsoCalendarDate "PyDateTime_IsoCalendarDate *" "&PyDateTime_IsoCalendarDateType"
  36. [clinic start generated code]*/
  37. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=81bec0fa19837f63]*/
  38. #include "clinic/_datetimemodule.c.h"
  39. /* We require that C int be at least 32 bits, and use int virtually
  40. * everywhere. In just a few cases we use a temp long, where a Python
  41. * API returns a C long. In such cases, we have to ensure that the
  42. * final result fits in a C int (this can be an issue on 64-bit boxes).
  43. */
  44. #if SIZEOF_INT < 4
  45. # error "_datetime.c requires that C int have at least 32 bits"
  46. #endif
  47. #define MINYEAR 1
  48. #define MAXYEAR 9999
  49. #define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
  50. /* Nine decimal digits is easy to communicate, and leaves enough room
  51. * so that two delta days can be added w/o fear of overflowing a signed
  52. * 32-bit int, and with plenty of room left over to absorb any possible
  53. * carries from adding seconds.
  54. */
  55. #define MAX_DELTA_DAYS 999999999
  56. /* Rename the long macros in datetime.h to more reasonable short names. */
  57. #define GET_YEAR PyDateTime_GET_YEAR
  58. #define GET_MONTH PyDateTime_GET_MONTH
  59. #define GET_DAY PyDateTime_GET_DAY
  60. #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
  61. #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
  62. #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
  63. #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
  64. #define DATE_GET_FOLD PyDateTime_DATE_GET_FOLD
  65. /* Date accessors for date and datetime. */
  66. #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
  67. ((o)->data[1] = ((v) & 0x00ff)))
  68. #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
  69. #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
  70. /* Date/Time accessors for datetime. */
  71. #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
  72. #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
  73. #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
  74. #define DATE_SET_MICROSECOND(o, v) \
  75. (((o)->data[7] = ((v) & 0xff0000) >> 16), \
  76. ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
  77. ((o)->data[9] = ((v) & 0x0000ff)))
  78. #define DATE_SET_FOLD(o, v) (PyDateTime_DATE_GET_FOLD(o) = (v))
  79. /* Time accessors for time. */
  80. #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
  81. #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
  82. #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
  83. #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
  84. #define TIME_GET_FOLD PyDateTime_TIME_GET_FOLD
  85. #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
  86. #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
  87. #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
  88. #define TIME_SET_MICROSECOND(o, v) \
  89. (((o)->data[3] = ((v) & 0xff0000) >> 16), \
  90. ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
  91. ((o)->data[5] = ((v) & 0x0000ff)))
  92. #define TIME_SET_FOLD(o, v) (PyDateTime_TIME_GET_FOLD(o) = (v))
  93. /* Delta accessors for timedelta. */
  94. #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
  95. #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
  96. #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
  97. #define SET_TD_DAYS(o, v) ((o)->days = (v))
  98. #define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
  99. #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
  100. #define HASTZINFO _PyDateTime_HAS_TZINFO
  101. #define GET_TIME_TZINFO PyDateTime_TIME_GET_TZINFO
  102. #define GET_DT_TZINFO PyDateTime_DATE_GET_TZINFO
  103. /* M is a char or int claiming to be a valid month. The macro is equivalent
  104. * to the two-sided Python test
  105. * 1 <= M <= 12
  106. */
  107. #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
  108. /* Forward declarations. */
  109. static PyTypeObject PyDateTime_DateType;
  110. static PyTypeObject PyDateTime_DateTimeType;
  111. static PyTypeObject PyDateTime_DeltaType;
  112. static PyTypeObject PyDateTime_IsoCalendarDateType;
  113. static PyTypeObject PyDateTime_TimeType;
  114. static PyTypeObject PyDateTime_TZInfoType;
  115. static PyTypeObject PyDateTime_TimeZoneType;
  116. static int check_tzinfo_subclass(PyObject *p);
  117. /* ---------------------------------------------------------------------------
  118. * Math utilities.
  119. */
  120. /* k = i+j overflows iff k differs in sign from both inputs,
  121. * iff k^i has sign bit set and k^j has sign bit set,
  122. * iff (k^i)&(k^j) has sign bit set.
  123. */
  124. #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
  125. ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
  126. /* Compute Python divmod(x, y), returning the quotient and storing the
  127. * remainder into *r. The quotient is the floor of x/y, and that's
  128. * the real point of this. C will probably truncate instead (C99
  129. * requires truncation; C89 left it implementation-defined).
  130. * Simplification: we *require* that y > 0 here. That's appropriate
  131. * for all the uses made of it. This simplifies the code and makes
  132. * the overflow case impossible (divmod(LONG_MIN, -1) is the only
  133. * overflow case).
  134. */
  135. static int
  136. divmod(int x, int y, int *r)
  137. {
  138. int quo;
  139. assert(y > 0);
  140. quo = x / y;
  141. *r = x - quo * y;
  142. if (*r < 0) {
  143. --quo;
  144. *r += y;
  145. }
  146. assert(0 <= *r && *r < y);
  147. return quo;
  148. }
  149. /* Nearest integer to m / n for integers m and n. Half-integer results
  150. * are rounded to even.
  151. */
  152. static PyObject *
  153. divide_nearest(PyObject *m, PyObject *n)
  154. {
  155. PyObject *result;
  156. PyObject *temp;
  157. temp = _PyLong_DivmodNear(m, n);
  158. if (temp == NULL)
  159. return NULL;
  160. result = Py_NewRef(PyTuple_GET_ITEM(temp, 0));
  161. Py_DECREF(temp);
  162. return result;
  163. }
  164. /* ---------------------------------------------------------------------------
  165. * General calendrical helper functions
  166. */
  167. /* For each month ordinal in 1..12, the number of days in that month,
  168. * and the number of days before that month in the same year. These
  169. * are correct for non-leap years only.
  170. */
  171. static const int _days_in_month[] = {
  172. 0, /* unused; this vector uses 1-based indexing */
  173. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  174. };
  175. static const int _days_before_month[] = {
  176. 0, /* unused; this vector uses 1-based indexing */
  177. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  178. };
  179. /* year -> 1 if leap year, else 0. */
  180. static int
  181. is_leap(int year)
  182. {
  183. /* Cast year to unsigned. The result is the same either way, but
  184. * C can generate faster code for unsigned mod than for signed
  185. * mod (especially for % 4 -- a good compiler should just grab
  186. * the last 2 bits when the LHS is unsigned).
  187. */
  188. const unsigned int ayear = (unsigned int)year;
  189. return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
  190. }
  191. /* year, month -> number of days in that month in that year */
  192. static int
  193. days_in_month(int year, int month)
  194. {
  195. assert(month >= 1);
  196. assert(month <= 12);
  197. if (month == 2 && is_leap(year))
  198. return 29;
  199. else
  200. return _days_in_month[month];
  201. }
  202. /* year, month -> number of days in year preceding first day of month */
  203. static int
  204. days_before_month(int year, int month)
  205. {
  206. int days;
  207. assert(month >= 1);
  208. assert(month <= 12);
  209. days = _days_before_month[month];
  210. if (month > 2 && is_leap(year))
  211. ++days;
  212. return days;
  213. }
  214. /* year -> number of days before January 1st of year. Remember that we
  215. * start with year 1, so days_before_year(1) == 0.
  216. */
  217. static int
  218. days_before_year(int year)
  219. {
  220. int y = year - 1;
  221. /* This is incorrect if year <= 0; we really want the floor
  222. * here. But so long as MINYEAR is 1, the smallest year this
  223. * can see is 1.
  224. */
  225. assert (year >= 1);
  226. return y*365 + y/4 - y/100 + y/400;
  227. }
  228. /* Number of days in 4, 100, and 400 year cycles. That these have
  229. * the correct values is asserted in the module init function.
  230. */
  231. #define DI4Y 1461 /* days_before_year(5); days in 4 years */
  232. #define DI100Y 36524 /* days_before_year(101); days in 100 years */
  233. #define DI400Y 146097 /* days_before_year(401); days in 400 years */
  234. /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
  235. static void
  236. ord_to_ymd(int ordinal, int *year, int *month, int *day)
  237. {
  238. int n, n1, n4, n100, n400, leapyear, preceding;
  239. /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
  240. * leap years repeats exactly every 400 years. The basic strategy is
  241. * to find the closest 400-year boundary at or before ordinal, then
  242. * work with the offset from that boundary to ordinal. Life is much
  243. * clearer if we subtract 1 from ordinal first -- then the values
  244. * of ordinal at 400-year boundaries are exactly those divisible
  245. * by DI400Y:
  246. *
  247. * D M Y n n-1
  248. * -- --- ---- ---------- ----------------
  249. * 31 Dec -400 -DI400Y -DI400Y -1
  250. * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
  251. * ...
  252. * 30 Dec 000 -1 -2
  253. * 31 Dec 000 0 -1
  254. * 1 Jan 001 1 0 400-year boundary
  255. * 2 Jan 001 2 1
  256. * 3 Jan 001 3 2
  257. * ...
  258. * 31 Dec 400 DI400Y DI400Y -1
  259. * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
  260. */
  261. assert(ordinal >= 1);
  262. --ordinal;
  263. n400 = ordinal / DI400Y;
  264. n = ordinal % DI400Y;
  265. *year = n400 * 400 + 1;
  266. /* Now n is the (non-negative) offset, in days, from January 1 of
  267. * year, to the desired date. Now compute how many 100-year cycles
  268. * precede n.
  269. * Note that it's possible for n100 to equal 4! In that case 4 full
  270. * 100-year cycles precede the desired day, which implies the
  271. * desired day is December 31 at the end of a 400-year cycle.
  272. */
  273. n100 = n / DI100Y;
  274. n = n % DI100Y;
  275. /* Now compute how many 4-year cycles precede it. */
  276. n4 = n / DI4Y;
  277. n = n % DI4Y;
  278. /* And now how many single years. Again n1 can be 4, and again
  279. * meaning that the desired day is December 31 at the end of the
  280. * 4-year cycle.
  281. */
  282. n1 = n / 365;
  283. n = n % 365;
  284. *year += n100 * 100 + n4 * 4 + n1;
  285. if (n1 == 4 || n100 == 4) {
  286. assert(n == 0);
  287. *year -= 1;
  288. *month = 12;
  289. *day = 31;
  290. return;
  291. }
  292. /* Now the year is correct, and n is the offset from January 1. We
  293. * find the month via an estimate that's either exact or one too
  294. * large.
  295. */
  296. leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
  297. assert(leapyear == is_leap(*year));
  298. *month = (n + 50) >> 5;
  299. preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
  300. if (preceding > n) {
  301. /* estimate is too large */
  302. *month -= 1;
  303. preceding -= days_in_month(*year, *month);
  304. }
  305. n -= preceding;
  306. assert(0 <= n);
  307. assert(n < days_in_month(*year, *month));
  308. *day = n + 1;
  309. }
  310. /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
  311. static int
  312. ymd_to_ord(int year, int month, int day)
  313. {
  314. return days_before_year(year) + days_before_month(year, month) + day;
  315. }
  316. /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
  317. static int
  318. weekday(int year, int month, int day)
  319. {
  320. return (ymd_to_ord(year, month, day) + 6) % 7;
  321. }
  322. /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
  323. * first calendar week containing a Thursday.
  324. */
  325. static int
  326. iso_week1_monday(int year)
  327. {
  328. int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
  329. /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
  330. int first_weekday = (first_day + 6) % 7;
  331. /* ordinal of closest Monday at or before 1/1 */
  332. int week1_monday = first_day - first_weekday;
  333. if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
  334. week1_monday += 7;
  335. return week1_monday;
  336. }
  337. static int
  338. iso_to_ymd(const int iso_year, const int iso_week, const int iso_day,
  339. int *year, int *month, int *day) {
  340. // Year is bounded to 0 < year < 10000 because 9999-12-31 is (9999, 52, 5)
  341. if (iso_year < MINYEAR || iso_year > MAXYEAR) {
  342. return -4;
  343. }
  344. if (iso_week <= 0 || iso_week >= 53) {
  345. int out_of_range = 1;
  346. if (iso_week == 53) {
  347. // ISO years have 53 weeks in it on years starting with a Thursday
  348. // and on leap years starting on Wednesday
  349. int first_weekday = weekday(iso_year, 1, 1);
  350. if (first_weekday == 3 || (first_weekday == 2 && is_leap(iso_year))) {
  351. out_of_range = 0;
  352. }
  353. }
  354. if (out_of_range) {
  355. return -2;
  356. }
  357. }
  358. if (iso_day <= 0 || iso_day >= 8) {
  359. return -3;
  360. }
  361. // Convert (Y, W, D) to (Y, M, D) in-place
  362. int day_1 = iso_week1_monday(iso_year);
  363. int day_offset = (iso_week - 1)*7 + iso_day - 1;
  364. ord_to_ymd(day_1 + day_offset, year, month, day);
  365. return 0;
  366. }
  367. /* ---------------------------------------------------------------------------
  368. * Range checkers.
  369. */
  370. /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
  371. * If not, raise OverflowError and return -1.
  372. */
  373. static int
  374. check_delta_day_range(int days)
  375. {
  376. if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
  377. return 0;
  378. PyErr_Format(PyExc_OverflowError,
  379. "days=%d; must have magnitude <= %d",
  380. days, MAX_DELTA_DAYS);
  381. return -1;
  382. }
  383. /* Check that date arguments are in range. Return 0 if they are. If they
  384. * aren't, raise ValueError and return -1.
  385. */
  386. static int
  387. check_date_args(int year, int month, int day)
  388. {
  389. if (year < MINYEAR || year > MAXYEAR) {
  390. PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
  391. return -1;
  392. }
  393. if (month < 1 || month > 12) {
  394. PyErr_SetString(PyExc_ValueError,
  395. "month must be in 1..12");
  396. return -1;
  397. }
  398. if (day < 1 || day > days_in_month(year, month)) {
  399. PyErr_SetString(PyExc_ValueError,
  400. "day is out of range for month");
  401. return -1;
  402. }
  403. return 0;
  404. }
  405. /* Check that time arguments are in range. Return 0 if they are. If they
  406. * aren't, raise ValueError and return -1.
  407. */
  408. static int
  409. check_time_args(int h, int m, int s, int us, int fold)
  410. {
  411. if (h < 0 || h > 23) {
  412. PyErr_SetString(PyExc_ValueError,
  413. "hour must be in 0..23");
  414. return -1;
  415. }
  416. if (m < 0 || m > 59) {
  417. PyErr_SetString(PyExc_ValueError,
  418. "minute must be in 0..59");
  419. return -1;
  420. }
  421. if (s < 0 || s > 59) {
  422. PyErr_SetString(PyExc_ValueError,
  423. "second must be in 0..59");
  424. return -1;
  425. }
  426. if (us < 0 || us > 999999) {
  427. PyErr_SetString(PyExc_ValueError,
  428. "microsecond must be in 0..999999");
  429. return -1;
  430. }
  431. if (fold != 0 && fold != 1) {
  432. PyErr_SetString(PyExc_ValueError,
  433. "fold must be either 0 or 1");
  434. return -1;
  435. }
  436. return 0;
  437. }
  438. /* ---------------------------------------------------------------------------
  439. * Normalization utilities.
  440. */
  441. /* One step of a mixed-radix conversion. A "hi" unit is equivalent to
  442. * factor "lo" units. factor must be > 0. If *lo is less than 0, or
  443. * at least factor, enough of *lo is converted into "hi" units so that
  444. * 0 <= *lo < factor. The input values must be such that int overflow
  445. * is impossible.
  446. */
  447. static void
  448. normalize_pair(int *hi, int *lo, int factor)
  449. {
  450. assert(factor > 0);
  451. assert(lo != hi);
  452. if (*lo < 0 || *lo >= factor) {
  453. const int num_hi = divmod(*lo, factor, lo);
  454. const int new_hi = *hi + num_hi;
  455. assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
  456. *hi = new_hi;
  457. }
  458. assert(0 <= *lo && *lo < factor);
  459. }
  460. /* Fiddle days (d), seconds (s), and microseconds (us) so that
  461. * 0 <= *s < 24*3600
  462. * 0 <= *us < 1000000
  463. * The input values must be such that the internals don't overflow.
  464. * The way this routine is used, we don't get close.
  465. */
  466. static void
  467. normalize_d_s_us(int *d, int *s, int *us)
  468. {
  469. if (*us < 0 || *us >= 1000000) {
  470. normalize_pair(s, us, 1000000);
  471. /* |s| can't be bigger than about
  472. * |original s| + |original us|/1000000 now.
  473. */
  474. }
  475. if (*s < 0 || *s >= 24*3600) {
  476. normalize_pair(d, s, 24*3600);
  477. /* |d| can't be bigger than about
  478. * |original d| +
  479. * (|original s| + |original us|/1000000) / (24*3600) now.
  480. */
  481. }
  482. assert(0 <= *s && *s < 24*3600);
  483. assert(0 <= *us && *us < 1000000);
  484. }
  485. /* Fiddle years (y), months (m), and days (d) so that
  486. * 1 <= *m <= 12
  487. * 1 <= *d <= days_in_month(*y, *m)
  488. * The input values must be such that the internals don't overflow.
  489. * The way this routine is used, we don't get close.
  490. */
  491. static int
  492. normalize_y_m_d(int *y, int *m, int *d)
  493. {
  494. int dim; /* # of days in month */
  495. /* In actual use, m is always the month component extracted from a
  496. * date/datetime object. Therefore it is always in [1, 12] range.
  497. */
  498. assert(1 <= *m && *m <= 12);
  499. /* Now only day can be out of bounds (year may also be out of bounds
  500. * for a datetime object, but we don't care about that here).
  501. * If day is out of bounds, what to do is arguable, but at least the
  502. * method here is principled and explainable.
  503. */
  504. dim = days_in_month(*y, *m);
  505. if (*d < 1 || *d > dim) {
  506. /* Move day-1 days from the first of the month. First try to
  507. * get off cheap if we're only one day out of range
  508. * (adjustments for timezone alone can't be worse than that).
  509. */
  510. if (*d == 0) {
  511. --*m;
  512. if (*m > 0)
  513. *d = days_in_month(*y, *m);
  514. else {
  515. --*y;
  516. *m = 12;
  517. *d = 31;
  518. }
  519. }
  520. else if (*d == dim + 1) {
  521. /* move forward a day */
  522. ++*m;
  523. *d = 1;
  524. if (*m > 12) {
  525. *m = 1;
  526. ++*y;
  527. }
  528. }
  529. else {
  530. int ordinal = ymd_to_ord(*y, *m, 1) +
  531. *d - 1;
  532. if (ordinal < 1 || ordinal > MAXORDINAL) {
  533. goto error;
  534. } else {
  535. ord_to_ymd(ordinal, y, m, d);
  536. return 0;
  537. }
  538. }
  539. }
  540. assert(*m > 0);
  541. assert(*d > 0);
  542. if (MINYEAR <= *y && *y <= MAXYEAR)
  543. return 0;
  544. error:
  545. PyErr_SetString(PyExc_OverflowError,
  546. "date value out of range");
  547. return -1;
  548. }
  549. /* Fiddle out-of-bounds months and days so that the result makes some kind
  550. * of sense. The parameters are both inputs and outputs. Returns < 0 on
  551. * failure, where failure means the adjusted year is out of bounds.
  552. */
  553. static int
  554. normalize_date(int *year, int *month, int *day)
  555. {
  556. return normalize_y_m_d(year, month, day);
  557. }
  558. /* Force all the datetime fields into range. The parameters are both
  559. * inputs and outputs. Returns < 0 on error.
  560. */
  561. static int
  562. normalize_datetime(int *year, int *month, int *day,
  563. int *hour, int *minute, int *second,
  564. int *microsecond)
  565. {
  566. normalize_pair(second, microsecond, 1000000);
  567. normalize_pair(minute, second, 60);
  568. normalize_pair(hour, minute, 60);
  569. normalize_pair(day, hour, 24);
  570. return normalize_date(year, month, day);
  571. }
  572. /* ---------------------------------------------------------------------------
  573. * Basic object allocation: tp_alloc implementations. These allocate
  574. * Python objects of the right size and type, and do the Python object-
  575. * initialization bit. If there's not enough memory, they return NULL after
  576. * setting MemoryError. All data members remain uninitialized trash.
  577. *
  578. * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
  579. * member is needed. This is ugly, imprecise, and possibly insecure.
  580. * tp_basicsize for the time and datetime types is set to the size of the
  581. * struct that has room for the tzinfo member, so subclasses in Python will
  582. * allocate enough space for a tzinfo member whether or not one is actually
  583. * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
  584. * part is that PyType_GenericAlloc() (which subclasses in Python end up
  585. * using) just happens today to effectively ignore the nitems argument
  586. * when tp_itemsize is 0, which it is for these type objects. If that
  587. * changes, perhaps the callers of tp_alloc slots in this file should
  588. * be changed to force a 0 nitems argument unless the type being allocated
  589. * is a base type implemented in this file (so that tp_alloc is time_alloc
  590. * or datetime_alloc below, which know about the nitems abuse).
  591. */
  592. static PyObject *
  593. time_alloc(PyTypeObject *type, Py_ssize_t aware)
  594. {
  595. size_t size = aware ? sizeof(PyDateTime_Time) : sizeof(_PyDateTime_BaseTime);
  596. PyObject *self = (PyObject *)PyObject_Malloc(size);
  597. if (self == NULL) {
  598. return PyErr_NoMemory();
  599. }
  600. _PyObject_Init(self, type);
  601. return self;
  602. }
  603. static PyObject *
  604. datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
  605. {
  606. size_t size = aware ? sizeof(PyDateTime_DateTime) : sizeof(_PyDateTime_BaseDateTime);
  607. PyObject *self = (PyObject *)PyObject_Malloc(size);
  608. if (self == NULL) {
  609. return PyErr_NoMemory();
  610. }
  611. _PyObject_Init(self, type);
  612. return self;
  613. }
  614. /* ---------------------------------------------------------------------------
  615. * Helpers for setting object fields. These work on pointers to the
  616. * appropriate base class.
  617. */
  618. /* For date and datetime. */
  619. static void
  620. set_date_fields(PyDateTime_Date *self, int y, int m, int d)
  621. {
  622. self->hashcode = -1;
  623. SET_YEAR(self, y);
  624. SET_MONTH(self, m);
  625. SET_DAY(self, d);
  626. }
  627. /* ---------------------------------------------------------------------------
  628. * String parsing utilities and helper functions
  629. */
  630. static unsigned char
  631. is_digit(const char c) {
  632. return ((unsigned int)(c - '0')) < 10;
  633. }
  634. static const char *
  635. parse_digits(const char *ptr, int *var, size_t num_digits)
  636. {
  637. for (size_t i = 0; i < num_digits; ++i) {
  638. unsigned int tmp = (unsigned int)(*(ptr++) - '0');
  639. if (tmp > 9) {
  640. return NULL;
  641. }
  642. *var *= 10;
  643. *var += (signed int)tmp;
  644. }
  645. return ptr;
  646. }
  647. static int
  648. parse_isoformat_date(const char *dtstr, const size_t len, int *year, int *month, int *day)
  649. {
  650. /* Parse the date components of the result of date.isoformat()
  651. *
  652. * Return codes:
  653. * 0: Success
  654. * -1: Failed to parse date component
  655. * -2: Inconsistent date separator usage
  656. * -3: Failed to parse ISO week.
  657. * -4: Failed to parse ISO day.
  658. * -5, -6, -7: Failure in iso_to_ymd
  659. */
  660. const char *p = dtstr;
  661. p = parse_digits(p, year, 4);
  662. if (NULL == p) {
  663. return -1;
  664. }
  665. const unsigned char uses_separator = (*p == '-');
  666. if (uses_separator) {
  667. ++p;
  668. }
  669. if(*p == 'W') {
  670. // This is an isocalendar-style date string
  671. p++;
  672. int iso_week = 0;
  673. int iso_day = 0;
  674. p = parse_digits(p, &iso_week, 2);
  675. if (NULL == p) {
  676. return -3;
  677. }
  678. assert(p > dtstr);
  679. if ((size_t)(p - dtstr) < len) {
  680. if (uses_separator && *(p++) != '-') {
  681. return -2;
  682. }
  683. p = parse_digits(p, &iso_day, 1);
  684. if (NULL == p) {
  685. return -4;
  686. }
  687. } else {
  688. iso_day = 1;
  689. }
  690. int rv = iso_to_ymd(*year, iso_week, iso_day, year, month, day);
  691. if (rv) {
  692. return -3 + rv;
  693. } else {
  694. return 0;
  695. }
  696. }
  697. p = parse_digits(p, month, 2);
  698. if (NULL == p) {
  699. return -1;
  700. }
  701. if (uses_separator && *(p++) != '-') {
  702. return -2;
  703. }
  704. p = parse_digits(p, day, 2);
  705. if (p == NULL) {
  706. return -1;
  707. }
  708. return 0;
  709. }
  710. static int
  711. parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
  712. int *minute, int *second, int *microsecond)
  713. {
  714. *hour = *minute = *second = *microsecond = 0;
  715. const char *p = tstr;
  716. const char *p_end = tstr_end;
  717. int *vals[3] = {hour, minute, second};
  718. // This is initialized to satisfy an erroneous compiler warning.
  719. unsigned char has_separator = 1;
  720. // Parse [HH[:?MM[:?SS]]]
  721. for (size_t i = 0; i < 3; ++i) {
  722. p = parse_digits(p, vals[i], 2);
  723. if (NULL == p) {
  724. return -3;
  725. }
  726. char c = *(p++);
  727. if (i == 0) {
  728. has_separator = (c == ':');
  729. }
  730. if (p >= p_end) {
  731. return c != '\0';
  732. }
  733. else if (has_separator && (c == ':')) {
  734. continue;
  735. }
  736. else if (c == '.' || c == ',') {
  737. break;
  738. } else if (!has_separator) {
  739. --p;
  740. } else {
  741. return -4; // Malformed time separator
  742. }
  743. }
  744. // Parse fractional components
  745. size_t len_remains = p_end - p;
  746. size_t to_parse = len_remains;
  747. if (len_remains >= 6) {
  748. to_parse = 6;
  749. }
  750. p = parse_digits(p, microsecond, to_parse);
  751. if (NULL == p) {
  752. return -3;
  753. }
  754. static int correction[] = {
  755. 100000, 10000, 1000, 100, 10
  756. };
  757. if (to_parse < 6) {
  758. *microsecond *= correction[to_parse-1];
  759. }
  760. while (is_digit(*p)){
  761. ++p; // skip truncated digits
  762. }
  763. // Return 1 if it's not the end of the string
  764. return *p != '\0';
  765. }
  766. static int
  767. parse_isoformat_time(const char *dtstr, size_t dtlen, int *hour, int *minute,
  768. int *second, int *microsecond, int *tzoffset,
  769. int *tzmicrosecond)
  770. {
  771. // Parse the time portion of a datetime.isoformat() string
  772. //
  773. // Return codes:
  774. // 0: Success (no tzoffset)
  775. // 1: Success (with tzoffset)
  776. // -3: Failed to parse time component
  777. // -4: Failed to parse time separator
  778. // -5: Malformed timezone string
  779. const char *p = dtstr;
  780. const char *p_end = dtstr + dtlen;
  781. const char *tzinfo_pos = p;
  782. do {
  783. if (*tzinfo_pos == 'Z' || *tzinfo_pos == '+' || *tzinfo_pos == '-') {
  784. break;
  785. }
  786. } while (++tzinfo_pos < p_end);
  787. int rv = parse_hh_mm_ss_ff(dtstr, tzinfo_pos, hour, minute, second,
  788. microsecond);
  789. if (rv < 0) {
  790. return rv;
  791. }
  792. else if (tzinfo_pos == p_end) {
  793. // We know that there's no time zone, so if there's stuff at the
  794. // end of the string it's an error.
  795. if (rv == 1) {
  796. return -5;
  797. }
  798. else {
  799. return 0;
  800. }
  801. }
  802. // Special case UTC / Zulu time.
  803. if (*tzinfo_pos == 'Z') {
  804. *tzoffset = 0;
  805. *tzmicrosecond = 0;
  806. if (*(tzinfo_pos + 1) != '\0') {
  807. return -5;
  808. } else {
  809. return 1;
  810. }
  811. }
  812. int tzsign = (*tzinfo_pos == '-') ? -1 : 1;
  813. tzinfo_pos++;
  814. int tzhour = 0, tzminute = 0, tzsecond = 0;
  815. rv = parse_hh_mm_ss_ff(tzinfo_pos, p_end, &tzhour, &tzminute, &tzsecond,
  816. tzmicrosecond);
  817. *tzoffset = tzsign * ((tzhour * 3600) + (tzminute * 60) + tzsecond);
  818. *tzmicrosecond *= tzsign;
  819. return rv ? -5 : 1;
  820. }
  821. /* ---------------------------------------------------------------------------
  822. * Create various objects, mostly without range checking.
  823. */
  824. /* Create a date instance with no range checking. */
  825. static PyObject *
  826. new_date_ex(int year, int month, int day, PyTypeObject *type)
  827. {
  828. PyDateTime_Date *self;
  829. if (check_date_args(year, month, day) < 0) {
  830. return NULL;
  831. }
  832. self = (PyDateTime_Date *)(type->tp_alloc(type, 0));
  833. if (self != NULL)
  834. set_date_fields(self, year, month, day);
  835. return (PyObject *)self;
  836. }
  837. #define new_date(year, month, day) \
  838. new_date_ex(year, month, day, &PyDateTime_DateType)
  839. // Forward declaration
  840. static PyObject *
  841. new_datetime_ex(int, int, int, int, int, int, int, PyObject *, PyTypeObject *);
  842. /* Create date instance with no range checking, or call subclass constructor */
  843. static PyObject *
  844. new_date_subclass_ex(int year, int month, int day, PyObject *cls)
  845. {
  846. PyObject *result;
  847. // We have "fast path" constructors for two subclasses: date and datetime
  848. if ((PyTypeObject *)cls == &PyDateTime_DateType) {
  849. result = new_date_ex(year, month, day, (PyTypeObject *)cls);
  850. }
  851. else if ((PyTypeObject *)cls == &PyDateTime_DateTimeType) {
  852. result = new_datetime_ex(year, month, day, 0, 0, 0, 0, Py_None,
  853. (PyTypeObject *)cls);
  854. }
  855. else {
  856. result = PyObject_CallFunction(cls, "iii", year, month, day);
  857. }
  858. return result;
  859. }
  860. /* Create a datetime instance with no range checking. */
  861. static PyObject *
  862. new_datetime_ex2(int year, int month, int day, int hour, int minute,
  863. int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
  864. {
  865. PyDateTime_DateTime *self;
  866. char aware = tzinfo != Py_None;
  867. if (check_date_args(year, month, day) < 0) {
  868. return NULL;
  869. }
  870. if (check_time_args(hour, minute, second, usecond, fold) < 0) {
  871. return NULL;
  872. }
  873. if (check_tzinfo_subclass(tzinfo) < 0) {
  874. return NULL;
  875. }
  876. self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
  877. if (self != NULL) {
  878. self->hastzinfo = aware;
  879. set_date_fields((PyDateTime_Date *)self, year, month, day);
  880. DATE_SET_HOUR(self, hour);
  881. DATE_SET_MINUTE(self, minute);
  882. DATE_SET_SECOND(self, second);
  883. DATE_SET_MICROSECOND(self, usecond);
  884. if (aware) {
  885. self->tzinfo = Py_NewRef(tzinfo);
  886. }
  887. DATE_SET_FOLD(self, fold);
  888. }
  889. return (PyObject *)self;
  890. }
  891. static PyObject *
  892. new_datetime_ex(int year, int month, int day, int hour, int minute,
  893. int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
  894. {
  895. return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
  896. tzinfo, 0, type);
  897. }
  898. #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
  899. new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
  900. &PyDateTime_DateTimeType)
  901. static PyObject *
  902. new_datetime_subclass_fold_ex(int year, int month, int day, int hour, int minute,
  903. int second, int usecond, PyObject *tzinfo,
  904. int fold, PyObject *cls) {
  905. PyObject* dt;
  906. if ((PyTypeObject*)cls == &PyDateTime_DateTimeType) {
  907. // Use the fast path constructor
  908. dt = new_datetime(year, month, day, hour, minute, second, usecond,
  909. tzinfo, fold);
  910. } else {
  911. // Subclass
  912. dt = PyObject_CallFunction(cls, "iiiiiiiO",
  913. year,
  914. month,
  915. day,
  916. hour,
  917. minute,
  918. second,
  919. usecond,
  920. tzinfo);
  921. }
  922. return dt;
  923. }
  924. static PyObject *
  925. new_datetime_subclass_ex(int year, int month, int day, int hour, int minute,
  926. int second, int usecond, PyObject *tzinfo,
  927. PyObject *cls) {
  928. return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
  929. second, usecond, tzinfo, 0,
  930. cls);
  931. }
  932. /* Create a time instance with no range checking. */
  933. static PyObject *
  934. new_time_ex2(int hour, int minute, int second, int usecond,
  935. PyObject *tzinfo, int fold, PyTypeObject *type)
  936. {
  937. PyDateTime_Time *self;
  938. char aware = tzinfo != Py_None;
  939. if (check_time_args(hour, minute, second, usecond, fold) < 0) {
  940. return NULL;
  941. }
  942. if (check_tzinfo_subclass(tzinfo) < 0) {
  943. return NULL;
  944. }
  945. self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
  946. if (self != NULL) {
  947. self->hastzinfo = aware;
  948. self->hashcode = -1;
  949. TIME_SET_HOUR(self, hour);
  950. TIME_SET_MINUTE(self, minute);
  951. TIME_SET_SECOND(self, second);
  952. TIME_SET_MICROSECOND(self, usecond);
  953. if (aware) {
  954. self->tzinfo = Py_NewRef(tzinfo);
  955. }
  956. TIME_SET_FOLD(self, fold);
  957. }
  958. return (PyObject *)self;
  959. }
  960. static PyObject *
  961. new_time_ex(int hour, int minute, int second, int usecond,
  962. PyObject *tzinfo, PyTypeObject *type)
  963. {
  964. return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
  965. }
  966. #define new_time(hh, mm, ss, us, tzinfo, fold) \
  967. new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
  968. /* Create a timedelta instance. Normalize the members iff normalize is
  969. * true. Passing false is a speed optimization, if you know for sure
  970. * that seconds and microseconds are already in their proper ranges. In any
  971. * case, raises OverflowError and returns NULL if the normalized days is out
  972. * of range.
  973. */
  974. static PyObject *
  975. new_delta_ex(int days, int seconds, int microseconds, int normalize,
  976. PyTypeObject *type)
  977. {
  978. PyDateTime_Delta *self;
  979. if (normalize)
  980. normalize_d_s_us(&days, &seconds, &microseconds);
  981. assert(0 <= seconds && seconds < 24*3600);
  982. assert(0 <= microseconds && microseconds < 1000000);
  983. if (check_delta_day_range(days) < 0)
  984. return NULL;
  985. self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
  986. if (self != NULL) {
  987. self->hashcode = -1;
  988. SET_TD_DAYS(self, days);
  989. SET_TD_SECONDS(self, seconds);
  990. SET_TD_MICROSECONDS(self, microseconds);
  991. }
  992. return (PyObject *) self;
  993. }
  994. #define new_delta(d, s, us, normalize) \
  995. new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
  996. typedef struct
  997. {
  998. PyObject_HEAD
  999. PyObject *offset;
  1000. PyObject *name;
  1001. } PyDateTime_TimeZone;
  1002. /* The interned UTC timezone instance */
  1003. static PyObject *PyDateTime_TimeZone_UTC;
  1004. /* The interned Epoch datetime instance */
  1005. static PyObject *PyDateTime_Epoch;
  1006. /* Create new timezone instance checking offset range. This
  1007. function does not check the name argument. Caller must assure
  1008. that offset is a timedelta instance and name is either NULL
  1009. or a unicode object. */
  1010. static PyObject *
  1011. create_timezone(PyObject *offset, PyObject *name)
  1012. {
  1013. PyDateTime_TimeZone *self;
  1014. PyTypeObject *type = &PyDateTime_TimeZoneType;
  1015. assert(offset != NULL);
  1016. assert(PyDelta_Check(offset));
  1017. assert(name == NULL || PyUnicode_Check(name));
  1018. self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
  1019. if (self == NULL) {
  1020. return NULL;
  1021. }
  1022. self->offset = Py_NewRef(offset);
  1023. self->name = Py_XNewRef(name);
  1024. return (PyObject *)self;
  1025. }
  1026. static int delta_bool(PyDateTime_Delta *self);
  1027. static PyObject *
  1028. new_timezone(PyObject *offset, PyObject *name)
  1029. {
  1030. assert(offset != NULL);
  1031. assert(PyDelta_Check(offset));
  1032. assert(name == NULL || PyUnicode_Check(name));
  1033. if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
  1034. return Py_NewRef(PyDateTime_TimeZone_UTC);
  1035. }
  1036. if ((GET_TD_DAYS(offset) == -1 &&
  1037. GET_TD_SECONDS(offset) == 0 &&
  1038. GET_TD_MICROSECONDS(offset) < 1) ||
  1039. GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
  1040. PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
  1041. " strictly between -timedelta(hours=24) and"
  1042. " timedelta(hours=24),"
  1043. " not %R.", offset);
  1044. return NULL;
  1045. }
  1046. return create_timezone(offset, name);
  1047. }
  1048. /* ---------------------------------------------------------------------------
  1049. * tzinfo helpers.
  1050. */
  1051. /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
  1052. * raise TypeError and return -1.
  1053. */
  1054. static int
  1055. check_tzinfo_subclass(PyObject *p)
  1056. {
  1057. if (p == Py_None || PyTZInfo_Check(p))
  1058. return 0;
  1059. PyErr_Format(PyExc_TypeError,
  1060. "tzinfo argument must be None or of a tzinfo subclass, "
  1061. "not type '%s'",
  1062. Py_TYPE(p)->tp_name);
  1063. return -1;
  1064. }
  1065. /* If self has a tzinfo member, return a BORROWED reference to it. Else
  1066. * return NULL, which is NOT AN ERROR. There are no error returns here,
  1067. * and the caller must not decref the result.
  1068. */
  1069. static PyObject *
  1070. get_tzinfo_member(PyObject *self)
  1071. {
  1072. PyObject *tzinfo = NULL;
  1073. if (PyDateTime_Check(self) && HASTZINFO(self))
  1074. tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
  1075. else if (PyTime_Check(self) && HASTZINFO(self))
  1076. tzinfo = ((PyDateTime_Time *)self)->tzinfo;
  1077. return tzinfo;
  1078. }
  1079. /* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
  1080. * be an instance of the tzinfo class. If the method returns None, this
  1081. * returns None. If the method doesn't return None or timedelta, TypeError is
  1082. * raised and this returns NULL. If it returns a timedelta and the value is
  1083. * out of range or isn't a whole number of minutes, ValueError is raised and
  1084. * this returns NULL. Else result is returned.
  1085. */
  1086. static PyObject *
  1087. call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
  1088. {
  1089. PyObject *offset;
  1090. assert(tzinfo != NULL);
  1091. assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
  1092. assert(tzinfoarg != NULL);
  1093. if (tzinfo == Py_None)
  1094. Py_RETURN_NONE;
  1095. offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
  1096. if (offset == Py_None || offset == NULL)
  1097. return offset;
  1098. if (PyDelta_Check(offset)) {
  1099. if ((GET_TD_DAYS(offset) == -1 &&
  1100. GET_TD_SECONDS(offset) == 0 &&
  1101. GET_TD_MICROSECONDS(offset) < 1) ||
  1102. GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
  1103. Py_DECREF(offset);
  1104. PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
  1105. " strictly between -timedelta(hours=24) and"
  1106. " timedelta(hours=24).");
  1107. return NULL;
  1108. }
  1109. }
  1110. else {
  1111. PyErr_Format(PyExc_TypeError,
  1112. "tzinfo.%s() must return None or "
  1113. "timedelta, not '%.200s'",
  1114. name, Py_TYPE(offset)->tp_name);
  1115. Py_DECREF(offset);
  1116. return NULL;
  1117. }
  1118. return offset;
  1119. }
  1120. /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
  1121. * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
  1122. * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
  1123. * doesn't return None or timedelta, TypeError is raised and this returns -1.
  1124. * If utcoffset() returns an out of range timedelta,
  1125. * ValueError is raised and this returns -1. Else *none is
  1126. * set to 0 and the offset is returned (as timedelta, positive east of UTC).
  1127. */
  1128. static PyObject *
  1129. call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
  1130. {
  1131. return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
  1132. }
  1133. /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
  1134. * result. tzinfo must be an instance of the tzinfo class. If dst()
  1135. * returns None, call_dst returns 0 and sets *none to 1. If dst()
  1136. * doesn't return None or timedelta, TypeError is raised and this
  1137. * returns -1. If dst() returns an invalid timedelta for a UTC offset,
  1138. * ValueError is raised and this returns -1. Else *none is set to 0 and
  1139. * the offset is returned (as timedelta, positive east of UTC).
  1140. */
  1141. static PyObject *
  1142. call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
  1143. {
  1144. return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
  1145. }
  1146. /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
  1147. * an instance of the tzinfo class or None. If tzinfo isn't None, and
  1148. * tzname() doesn't return None or a string, TypeError is raised and this
  1149. * returns NULL. If the result is a string, we ensure it is a Unicode
  1150. * string.
  1151. */
  1152. static PyObject *
  1153. call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
  1154. {
  1155. PyObject *result;
  1156. assert(tzinfo != NULL);
  1157. assert(check_tzinfo_subclass(tzinfo) >= 0);
  1158. assert(tzinfoarg != NULL);
  1159. if (tzinfo == Py_None)
  1160. Py_RETURN_NONE;
  1161. result = PyObject_CallMethodOneArg(tzinfo, &_Py_ID(tzname), tzinfoarg);
  1162. if (result == NULL || result == Py_None)
  1163. return result;
  1164. if (!PyUnicode_Check(result)) {
  1165. PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
  1166. "return None or a string, not '%s'",
  1167. Py_TYPE(result)->tp_name);
  1168. Py_SETREF(result, NULL);
  1169. }
  1170. return result;
  1171. }
  1172. /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
  1173. * stuff
  1174. * ", tzinfo=" + repr(tzinfo)
  1175. * before the closing ")".
  1176. */
  1177. static PyObject *
  1178. append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
  1179. {
  1180. PyObject *temp;
  1181. assert(PyUnicode_Check(repr));
  1182. assert(tzinfo);
  1183. if (tzinfo == Py_None)
  1184. return repr;
  1185. /* Get rid of the trailing ')'. */
  1186. assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
  1187. temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
  1188. Py_DECREF(repr);
  1189. if (temp == NULL)
  1190. return NULL;
  1191. repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
  1192. Py_DECREF(temp);
  1193. return repr;
  1194. }
  1195. /* repr is like "someclass(arg1, arg2)". If fold isn't 0,
  1196. * stuff
  1197. * ", fold=" + repr(tzinfo)
  1198. * before the closing ")".
  1199. */
  1200. static PyObject *
  1201. append_keyword_fold(PyObject *repr, int fold)
  1202. {
  1203. PyObject *temp;
  1204. assert(PyUnicode_Check(repr));
  1205. if (fold == 0)
  1206. return repr;
  1207. /* Get rid of the trailing ')'. */
  1208. assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
  1209. temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
  1210. Py_DECREF(repr);
  1211. if (temp == NULL)
  1212. return NULL;
  1213. repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
  1214. Py_DECREF(temp);
  1215. return repr;
  1216. }
  1217. static inline PyObject *
  1218. tzinfo_from_isoformat_results(int rv, int tzoffset, int tz_useconds)
  1219. {
  1220. PyObject *tzinfo;
  1221. if (rv == 1) {
  1222. // Create a timezone from offset in seconds (0 returns UTC)
  1223. if (tzoffset == 0) {
  1224. return Py_NewRef(PyDateTime_TimeZone_UTC);
  1225. }
  1226. PyObject *delta = new_delta(0, tzoffset, tz_useconds, 1);
  1227. if (delta == NULL) {
  1228. return NULL;
  1229. }
  1230. tzinfo = new_timezone(delta, NULL);
  1231. Py_DECREF(delta);
  1232. }
  1233. else {
  1234. tzinfo = Py_NewRef(Py_None);
  1235. }
  1236. return tzinfo;
  1237. }
  1238. /* ---------------------------------------------------------------------------
  1239. * String format helpers.
  1240. */
  1241. static PyObject *
  1242. format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
  1243. {
  1244. static const char * const DayNames[] = {
  1245. "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
  1246. };
  1247. static const char * const MonthNames[] = {
  1248. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1249. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  1250. };
  1251. int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
  1252. return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
  1253. DayNames[wday], MonthNames[GET_MONTH(date)-1],
  1254. GET_DAY(date), hours, minutes, seconds,
  1255. GET_YEAR(date));
  1256. }
  1257. static PyObject *delta_negative(PyDateTime_Delta *self);
  1258. /* Add formatted UTC offset string to buf. buf has no more than
  1259. * buflen bytes remaining. The UTC offset is gotten by calling
  1260. * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
  1261. * *buf, and that's all. Else the returned value is checked for sanity (an
  1262. * integer in range), and if that's OK it's converted to an hours & minutes
  1263. * string of the form
  1264. * sign HH sep MM [sep SS [. UUUUUU]]
  1265. * Returns 0 if everything is OK. If the return value from utcoffset() is
  1266. * bogus, an appropriate exception is set and -1 is returned.
  1267. */
  1268. static int
  1269. format_utcoffset(char *buf, size_t buflen, const char *sep,
  1270. PyObject *tzinfo, PyObject *tzinfoarg)
  1271. {
  1272. PyObject *offset;
  1273. int hours, minutes, seconds, microseconds;
  1274. char sign;
  1275. assert(buflen >= 1);
  1276. offset = call_utcoffset(tzinfo, tzinfoarg);
  1277. if (offset == NULL)
  1278. return -1;
  1279. if (offset == Py_None) {
  1280. Py_DECREF(offset);
  1281. *buf = '\0';
  1282. return 0;
  1283. }
  1284. /* Offset is normalized, so it is negative if days < 0 */
  1285. if (GET_TD_DAYS(offset) < 0) {
  1286. sign = '-';
  1287. Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
  1288. if (offset == NULL)
  1289. return -1;
  1290. }
  1291. else {
  1292. sign = '+';
  1293. }
  1294. /* Offset is not negative here. */
  1295. microseconds = GET_TD_MICROSECONDS(offset);
  1296. seconds = GET_TD_SECONDS(offset);
  1297. Py_DECREF(offset);
  1298. minutes = divmod(seconds, 60, &seconds);
  1299. hours = divmod(minutes, 60, &minutes);
  1300. if (microseconds) {
  1301. PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d.%06d", sign,
  1302. hours, sep, minutes, sep, seconds, microseconds);
  1303. return 0;
  1304. }
  1305. if (seconds) {
  1306. PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
  1307. sep, minutes, sep, seconds);
  1308. return 0;
  1309. }
  1310. PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
  1311. return 0;
  1312. }
  1313. static PyObject *
  1314. make_somezreplacement(PyObject *object, char *sep, PyObject *tzinfoarg)
  1315. {
  1316. char buf[100];
  1317. PyObject *tzinfo = get_tzinfo_member(object);
  1318. if (tzinfo == Py_None || tzinfo == NULL) {
  1319. return PyBytes_FromStringAndSize(NULL, 0);
  1320. }
  1321. assert(tzinfoarg != NULL);
  1322. if (format_utcoffset(buf,
  1323. sizeof(buf),
  1324. sep,
  1325. tzinfo,
  1326. tzinfoarg) < 0)
  1327. return NULL;
  1328. return PyBytes_FromStringAndSize(buf, strlen(buf));
  1329. }
  1330. static PyObject *
  1331. make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
  1332. {
  1333. PyObject *temp;
  1334. PyObject *tzinfo = get_tzinfo_member(object);
  1335. PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
  1336. if (Zreplacement == NULL)
  1337. return NULL;
  1338. if (tzinfo == Py_None || tzinfo == NULL)
  1339. return Zreplacement;
  1340. assert(tzinfoarg != NULL);
  1341. temp = call_tzname(tzinfo, tzinfoarg);
  1342. if (temp == NULL)
  1343. goto Error;
  1344. if (temp == Py_None) {
  1345. Py_DECREF(temp);
  1346. return Zreplacement;
  1347. }
  1348. assert(PyUnicode_Check(temp));
  1349. /* Since the tzname is getting stuffed into the
  1350. * format, we have to double any % signs so that
  1351. * strftime doesn't treat them as format codes.
  1352. */
  1353. Py_DECREF(Zreplacement);
  1354. Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
  1355. Py_DECREF(temp);
  1356. if (Zreplacement == NULL)
  1357. return NULL;
  1358. if (!PyUnicode_Check(Zreplacement)) {
  1359. PyErr_SetString(PyExc_TypeError,
  1360. "tzname.replace() did not return a string");
  1361. goto Error;
  1362. }
  1363. return Zreplacement;
  1364. Error:
  1365. Py_DECREF(Zreplacement);
  1366. return NULL;
  1367. }
  1368. static PyObject *
  1369. make_freplacement(PyObject *object)
  1370. {
  1371. char freplacement[64];
  1372. if (PyTime_Check(object))
  1373. sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
  1374. else if (PyDateTime_Check(object))
  1375. sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
  1376. else
  1377. sprintf(freplacement, "%06d", 0);
  1378. return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
  1379. }
  1380. /* I sure don't want to reproduce the strftime code from the time module,
  1381. * so this imports the module and calls it. All the hair is due to
  1382. * giving special meanings to the %z, %:z, %Z and %f format codes via a
  1383. * preprocessing step on the format string.
  1384. * tzinfoarg is the argument to pass to the object's tzinfo method, if
  1385. * needed.
  1386. */
  1387. static PyObject *
  1388. wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
  1389. PyObject *tzinfoarg)
  1390. {
  1391. PyObject *result = NULL; /* guilty until proved innocent */
  1392. PyObject *zreplacement = NULL; /* py string, replacement for %z */
  1393. PyObject *colonzreplacement = NULL; /* py string, replacement for %:z */
  1394. PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
  1395. PyObject *freplacement = NULL; /* py string, replacement for %f */
  1396. const char *pin; /* pointer to next char in input format */
  1397. Py_ssize_t flen; /* length of input format */
  1398. char ch; /* next char in input format */
  1399. PyObject *newfmt = NULL; /* py string, the output format */
  1400. char *pnew; /* pointer to available byte in output format */
  1401. size_t totalnew; /* number bytes total in output format buffer,
  1402. exclusive of trailing \0 */
  1403. size_t usednew; /* number bytes used so far in output format buffer */
  1404. const char *ptoappend; /* ptr to string to append to output buffer */
  1405. Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
  1406. assert(object && format && timetuple);
  1407. assert(PyUnicode_Check(format));
  1408. /* Convert the input format to a C string and size */
  1409. pin = PyUnicode_AsUTF8AndSize(format, &flen);
  1410. if (!pin)
  1411. return NULL;
  1412. /* Scan the input format, looking for %z/%Z/%f escapes, building
  1413. * a new format. Since computing the replacements for those codes
  1414. * is expensive, don't unless they're actually used.
  1415. */
  1416. if (flen > INT_MAX - 1) {
  1417. PyErr_NoMemory();
  1418. goto Done;
  1419. }
  1420. totalnew = flen + 1; /* realistic if no %z/%Z */
  1421. newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
  1422. if (newfmt == NULL) goto Done;
  1423. pnew = PyBytes_AsString(newfmt);
  1424. usednew = 0;
  1425. while ((ch = *pin++) != '\0') {
  1426. if (ch != '%') {
  1427. ptoappend = pin - 1;
  1428. ntoappend = 1;
  1429. }
  1430. else if ((ch = *pin++) == '\0') {
  1431. /* Null byte follows %, copy only '%'.
  1432. *
  1433. * Back the pin up one char so that we catch the null check
  1434. * the next time through the loop.*/
  1435. pin--;
  1436. ptoappend = pin - 1;
  1437. ntoappend = 1;
  1438. }
  1439. /* A % has been seen and ch is the character after it. */
  1440. else if (ch == 'z') {
  1441. /* %z -> +HHMM */
  1442. if (zreplacement == NULL) {
  1443. zreplacement = make_somezreplacement(object, "", tzinfoarg);
  1444. if (zreplacement == NULL)
  1445. goto Done;
  1446. }
  1447. assert(zreplacement != NULL);
  1448. assert(PyBytes_Check(zreplacement));
  1449. ptoappend = PyBytes_AS_STRING(zreplacement);
  1450. ntoappend = PyBytes_GET_SIZE(zreplacement);
  1451. }
  1452. else if (ch == ':' && *pin == 'z' && pin++) {
  1453. /* %:z -> +HH:MM */
  1454. if (colonzreplacement == NULL) {
  1455. colonzreplacement = make_somezreplacement(object, ":", tzinfoarg);
  1456. if (colonzreplacement == NULL)
  1457. goto Done;
  1458. }
  1459. assert(colonzreplacement != NULL);
  1460. assert(PyBytes_Check(colonzreplacement));
  1461. ptoappend = PyBytes_AS_STRING(colonzreplacement);
  1462. ntoappend = PyBytes_GET_SIZE(colonzreplacement);
  1463. }
  1464. else if (ch == 'Z') {
  1465. /* format tzname */
  1466. if (Zreplacement == NULL) {
  1467. Zreplacement = make_Zreplacement(object,
  1468. tzinfoarg);
  1469. if (Zreplacement == NULL)
  1470. goto Done;
  1471. }
  1472. assert(Zreplacement != NULL);
  1473. assert(PyUnicode_Check(Zreplacement));
  1474. ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
  1475. &ntoappend);
  1476. if (ptoappend == NULL)
  1477. goto Done;
  1478. }
  1479. else if (ch == 'f') {
  1480. /* format microseconds */
  1481. if (freplacement == NULL) {
  1482. freplacement = make_freplacement(object);
  1483. if (freplacement == NULL)
  1484. goto Done;
  1485. }
  1486. assert(freplacement != NULL);
  1487. assert(PyBytes_Check(freplacement));
  1488. ptoappend = PyBytes_AS_STRING(freplacement);
  1489. ntoappend = PyBytes_GET_SIZE(freplacement);
  1490. }
  1491. else {
  1492. /* percent followed by something else */
  1493. ptoappend = pin - 2;
  1494. ntoappend = 2;
  1495. }
  1496. /* Append the ntoappend chars starting at ptoappend to
  1497. * the new format.
  1498. */
  1499. if (ntoappend == 0)
  1500. continue;
  1501. assert(ptoappend != NULL);
  1502. assert(ntoappend > 0);
  1503. while (usednew + ntoappend > totalnew) {
  1504. if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
  1505. PyErr_NoMemory();
  1506. goto Done;
  1507. }
  1508. totalnew <<= 1;
  1509. if (_PyBytes_Resize(&newfmt, totalnew) < 0)
  1510. goto Done;
  1511. pnew = PyBytes_AsString(newfmt) + usednew;
  1512. }
  1513. memcpy(pnew, ptoappend, ntoappend);
  1514. pnew += ntoappend;
  1515. usednew += ntoappend;
  1516. assert(usednew <= totalnew);
  1517. } /* end while() */
  1518. if (_PyBytes_Resize(&newfmt, usednew) < 0)
  1519. goto Done;
  1520. {
  1521. PyObject *format;
  1522. PyObject *strftime = _PyImport_GetModuleAttrString("time", "strftime");
  1523. if (strftime == NULL)
  1524. goto Done;
  1525. format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
  1526. if (format != NULL) {
  1527. result = PyObject_CallFunctionObjArgs(strftime,
  1528. format, timetuple, NULL);
  1529. Py_DECREF(format);
  1530. }
  1531. Py_DECREF(strftime);
  1532. }
  1533. Done:
  1534. Py_XDECREF(freplacement);
  1535. Py_XDECREF(zreplacement);
  1536. Py_XDECREF(colonzreplacement);
  1537. Py_XDECREF(Zreplacement);
  1538. Py_XDECREF(newfmt);
  1539. return result;
  1540. }
  1541. /* ---------------------------------------------------------------------------
  1542. * Wrap functions from the time module. These aren't directly available
  1543. * from C. Perhaps they should be.
  1544. */
  1545. /* Call time.time() and return its result (a Python float). */
  1546. static PyObject *
  1547. time_time(void)
  1548. {
  1549. PyObject *result = NULL;
  1550. PyObject *time = _PyImport_GetModuleAttrString("time", "time");
  1551. if (time != NULL) {
  1552. result = PyObject_CallNoArgs(time);
  1553. Py_DECREF(time);
  1554. }
  1555. return result;
  1556. }
  1557. /* Build a time.struct_time. The weekday and day number are automatically
  1558. * computed from the y,m,d args.
  1559. */
  1560. static PyObject *
  1561. build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
  1562. {
  1563. PyObject *struct_time;
  1564. PyObject *result;
  1565. struct_time = _PyImport_GetModuleAttrString("time", "struct_time");
  1566. if (struct_time == NULL) {
  1567. return NULL;
  1568. }
  1569. result = PyObject_CallFunction(struct_time, "((iiiiiiiii))",
  1570. y, m, d,
  1571. hh, mm, ss,
  1572. weekday(y, m, d),
  1573. days_before_month(y, m) + d,
  1574. dstflag);
  1575. Py_DECREF(struct_time);
  1576. return result;
  1577. }
  1578. /* ---------------------------------------------------------------------------
  1579. * Miscellaneous helpers.
  1580. */
  1581. /* The comparisons here all most naturally compute a cmp()-like result.
  1582. * This little helper turns that into a bool result for rich comparisons.
  1583. */
  1584. static PyObject *
  1585. diff_to_bool(int diff, int op)
  1586. {
  1587. Py_RETURN_RICHCOMPARE(diff, 0, op);
  1588. }
  1589. /* Raises a "can't compare" TypeError and returns NULL. */
  1590. static PyObject *
  1591. cmperror(PyObject *a, PyObject *b)
  1592. {
  1593. PyErr_Format(PyExc_TypeError,
  1594. "can't compare %s to %s",
  1595. Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
  1596. return NULL;
  1597. }
  1598. /* ---------------------------------------------------------------------------
  1599. * Cached Python objects; these are set by the module init function.
  1600. */
  1601. /* Conversion factors. */
  1602. static PyObject *us_per_ms = NULL; /* 1000 */
  1603. static PyObject *us_per_second = NULL; /* 1000000 */
  1604. static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
  1605. static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
  1606. static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
  1607. static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
  1608. static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
  1609. /* ---------------------------------------------------------------------------
  1610. * Class implementations.
  1611. */
  1612. /*
  1613. * PyDateTime_Delta implementation.
  1614. */
  1615. /* Convert a timedelta to a number of us,
  1616. * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
  1617. * as a Python int.
  1618. * Doing mixed-radix arithmetic by hand instead is excruciating in C,
  1619. * due to ubiquitous overflow possibilities.
  1620. */
  1621. static PyObject *
  1622. delta_to_microseconds(PyDateTime_Delta *self)
  1623. {
  1624. PyObject *x1 = NULL;
  1625. PyObject *x2 = NULL;
  1626. PyObject *x3 = NULL;
  1627. PyObject *result = NULL;
  1628. x1 = PyLong_FromLong(GET_TD_DAYS(self));
  1629. if (x1 == NULL)
  1630. goto Done;
  1631. x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
  1632. if (x2 == NULL)
  1633. goto Done;
  1634. Py_SETREF(x1, NULL);
  1635. /* x2 has days in seconds */
  1636. x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
  1637. if (x1 == NULL)
  1638. goto Done;
  1639. x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
  1640. if (x3 == NULL)
  1641. goto Done;
  1642. Py_DECREF(x1);
  1643. Py_DECREF(x2);
  1644. /* x1 = */ x2 = NULL;
  1645. /* x3 has days+seconds in seconds */
  1646. x1 = PyNumber_Multiply(x3, us_per_second); /* us */
  1647. if (x1 == NULL)
  1648. goto Done;
  1649. Py_SETREF(x3, NULL);
  1650. /* x1 has days+seconds in us */
  1651. x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
  1652. if (x2 == NULL)
  1653. goto Done;
  1654. result = PyNumber_Add(x1, x2);
  1655. assert(result == NULL || PyLong_CheckExact(result));
  1656. Done:
  1657. Py_XDECREF(x1);
  1658. Py_XDECREF(x2);
  1659. Py_XDECREF(x3);
  1660. return result;
  1661. }
  1662. static PyObject *
  1663. checked_divmod(PyObject *a, PyObject *b)
  1664. {
  1665. PyObject *result = PyNumber_Divmod(a, b);
  1666. if (result != NULL) {
  1667. if (!PyTuple_Check(result)) {
  1668. PyErr_Format(PyExc_TypeError,
  1669. "divmod() returned non-tuple (type %.200s)",
  1670. Py_TYPE(result)->tp_name);
  1671. Py_DECREF(result);
  1672. return NULL;
  1673. }
  1674. if (PyTuple_GET_SIZE(result) != 2) {
  1675. PyErr_Format(PyExc_TypeError,
  1676. "divmod() returned a tuple of size %zd",
  1677. PyTuple_GET_SIZE(result));
  1678. Py_DECREF(result);
  1679. return NULL;
  1680. }
  1681. }
  1682. return result;
  1683. }
  1684. /* Convert a number of us (as a Python int) to a timedelta.
  1685. */
  1686. static PyObject *
  1687. microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
  1688. {
  1689. int us;
  1690. int s;
  1691. int d;
  1692. PyObject *tuple = NULL;
  1693. PyObject *num = NULL;
  1694. PyObject *result = NULL;
  1695. tuple = checked_divmod(pyus, us_per_second);
  1696. if (tuple == NULL) {
  1697. goto Done;
  1698. }
  1699. num = PyTuple_GET_ITEM(tuple, 1); /* us */
  1700. us = _PyLong_AsInt(num);
  1701. num = NULL;
  1702. if (us == -1 && PyErr_Occurred()) {
  1703. goto Done;
  1704. }
  1705. if (!(0 <= us && us < 1000000)) {
  1706. goto BadDivmod;
  1707. }
  1708. num = Py_NewRef(PyTuple_GET_ITEM(tuple, 0)); /* leftover seconds */
  1709. Py_DECREF(tuple);
  1710. tuple = checked_divmod(num, seconds_per_day);
  1711. if (tuple == NULL)
  1712. goto Done;
  1713. Py_DECREF(num);
  1714. num = PyTuple_GET_ITEM(tuple, 1); /* seconds */
  1715. s = _PyLong_AsInt(num);
  1716. num = NULL;
  1717. if (s == -1 && PyErr_Occurred()) {
  1718. goto Done;
  1719. }
  1720. if (!(0 <= s && s < 24*3600)) {
  1721. goto BadDivmod;
  1722. }
  1723. num = Py_NewRef(PyTuple_GET_ITEM(tuple, 0)); /* leftover days */
  1724. d = _PyLong_AsInt(num);
  1725. if (d == -1 && PyErr_Occurred()) {
  1726. goto Done;
  1727. }
  1728. result = new_delta_ex(d, s, us, 0, type);
  1729. Done:
  1730. Py_XDECREF(tuple);
  1731. Py_XDECREF(num);
  1732. return result;
  1733. BadDivmod:
  1734. PyErr_SetString(PyExc_TypeError,
  1735. "divmod() returned a value out of range");
  1736. goto Done;
  1737. }
  1738. #define microseconds_to_delta(pymicros) \
  1739. microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
  1740. static PyObject *
  1741. multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
  1742. {
  1743. PyObject *pyus_in;
  1744. PyObject *pyus_out;
  1745. PyObject *result;
  1746. pyus_in = delta_to_microseconds(delta);
  1747. if (pyus_in == NULL)
  1748. return NULL;
  1749. pyus_out = PyNumber_Multiply(intobj, pyus_in);
  1750. Py_DECREF(pyus_in);
  1751. if (pyus_out == NULL)
  1752. return NULL;
  1753. result = microseconds_to_delta(pyus_out);
  1754. Py_DECREF(pyus_out);
  1755. return result;
  1756. }
  1757. static PyObject *
  1758. get_float_as_integer_ratio(PyObject *floatobj)
  1759. {
  1760. PyObject *ratio;
  1761. assert(floatobj && PyFloat_Check(floatobj));
  1762. ratio = PyObject_CallMethodNoArgs(floatobj, &_Py_ID(as_integer_ratio));
  1763. if (ratio == NULL) {
  1764. return NULL;
  1765. }
  1766. if (!PyTuple_Check(ratio)) {
  1767. PyErr_Format(PyExc_TypeError,
  1768. "unexpected return type from as_integer_ratio(): "
  1769. "expected tuple, got '%.200s'",
  1770. Py_TYPE(ratio)->tp_name);
  1771. Py_DECREF(ratio);
  1772. return NULL;
  1773. }
  1774. if (PyTuple_Size(ratio) != 2) {
  1775. PyErr_SetString(PyExc_ValueError,
  1776. "as_integer_ratio() must return a 2-tuple");
  1777. Py_DECREF(ratio);
  1778. return NULL;
  1779. }
  1780. return ratio;
  1781. }
  1782. /* op is 0 for multiplication, 1 for division */
  1783. static PyObject *
  1784. multiply_truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *floatobj, int op)
  1785. {
  1786. PyObject *result = NULL;
  1787. PyObject *pyus_in = NULL, *temp, *pyus_out;
  1788. PyObject *ratio = NULL;
  1789. pyus_in = delta_to_microseconds(delta);
  1790. if (pyus_in == NULL)
  1791. return NULL;
  1792. ratio = get_float_as_integer_ratio(floatobj);
  1793. if (ratio == NULL) {
  1794. goto error;
  1795. }
  1796. temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, op));
  1797. Py_SETREF(pyus_in, NULL);
  1798. if (temp == NULL)
  1799. goto error;
  1800. pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, !op));
  1801. Py_DECREF(temp);
  1802. if (pyus_out == NULL)
  1803. goto error;
  1804. result = microseconds_to_delta(pyus_out);
  1805. Py_DECREF(pyus_out);
  1806. error:
  1807. Py_XDECREF(pyus_in);
  1808. Py_XDECREF(ratio);
  1809. return result;
  1810. }
  1811. static PyObject *
  1812. divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
  1813. {
  1814. PyObject *pyus_in;
  1815. PyObject *pyus_out;
  1816. PyObject *result;
  1817. pyus_in = delta_to_microseconds(delta);
  1818. if (pyus_in == NULL)
  1819. return NULL;
  1820. pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
  1821. Py_DECREF(pyus_in);
  1822. if (pyus_out == NULL)
  1823. return NULL;
  1824. result = microseconds_to_delta(pyus_out);
  1825. Py_DECREF(pyus_out);
  1826. return result;
  1827. }
  1828. static PyObject *
  1829. divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
  1830. {
  1831. PyObject *pyus_left;
  1832. PyObject *pyus_right;
  1833. PyObject *result;
  1834. pyus_left = delta_to_microseconds(left);
  1835. if (pyus_left == NULL)
  1836. return NULL;
  1837. pyus_right = delta_to_microseconds(right);
  1838. if (pyus_right == NULL) {
  1839. Py_DECREF(pyus_left);
  1840. return NULL;
  1841. }
  1842. result = PyNumber_FloorDivide(pyus_left, pyus_right);
  1843. Py_DECREF(pyus_left);
  1844. Py_DECREF(pyus_right);
  1845. return result;
  1846. }
  1847. static PyObject *
  1848. truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
  1849. {
  1850. PyObject *pyus_left;
  1851. PyObject *pyus_right;
  1852. PyObject *result;
  1853. pyus_left = delta_to_microseconds(left);
  1854. if (pyus_left == NULL)
  1855. return NULL;
  1856. pyus_right = delta_to_microseconds(right);
  1857. if (pyus_right == NULL) {
  1858. Py_DECREF(pyus_left);
  1859. return NULL;
  1860. }
  1861. result = PyNumber_TrueDivide(pyus_left, pyus_right);
  1862. Py_DECREF(pyus_left);
  1863. Py_DECREF(pyus_right);
  1864. return result;
  1865. }
  1866. static PyObject *
  1867. truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
  1868. {
  1869. PyObject *result;
  1870. PyObject *pyus_in, *pyus_out;
  1871. pyus_in = delta_to_microseconds(delta);
  1872. if (pyus_in == NULL)
  1873. return NULL;
  1874. pyus_out = divide_nearest(pyus_in, i);
  1875. Py_DECREF(pyus_in);
  1876. if (pyus_out == NULL)
  1877. return NULL;
  1878. result = microseconds_to_delta(pyus_out);
  1879. Py_DECREF(pyus_out);
  1880. return result;
  1881. }
  1882. static PyObject *
  1883. delta_add(PyObject *left, PyObject *right)
  1884. {
  1885. PyObject *result = Py_NotImplemented;
  1886. if (PyDelta_Check(left) && PyDelta_Check(right)) {
  1887. /* delta + delta */
  1888. /* The C-level additions can't overflow because of the
  1889. * invariant bounds.
  1890. */
  1891. int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
  1892. int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
  1893. int microseconds = GET_TD_MICROSECONDS(left) +
  1894. GET_TD_MICROSECONDS(right);
  1895. result = new_delta(days, seconds, microseconds, 1);
  1896. }
  1897. if (result == Py_NotImplemented)
  1898. Py_INCREF(result);
  1899. return result;
  1900. }
  1901. static PyObject *
  1902. delta_negative(PyDateTime_Delta *self)
  1903. {
  1904. return new_delta(-GET_TD_DAYS(self),
  1905. -GET_TD_SECONDS(self),
  1906. -GET_TD_MICROSECONDS(self),
  1907. 1);
  1908. }
  1909. static PyObject *
  1910. delta_positive(PyDateTime_Delta *self)
  1911. {
  1912. /* Could optimize this (by returning self) if this isn't a
  1913. * subclass -- but who uses unary + ? Approximately nobody.
  1914. */
  1915. return new_delta(GET_TD_DAYS(self),
  1916. GET_TD_SECONDS(self),
  1917. GET_TD_MICROSECONDS(self),
  1918. 0);
  1919. }
  1920. static PyObject *
  1921. delta_abs(PyDateTime_Delta *self)
  1922. {
  1923. PyObject *result;
  1924. assert(GET_TD_MICROSECONDS(self) >= 0);
  1925. assert(GET_TD_SECONDS(self) >= 0);
  1926. if (GET_TD_DAYS(self) < 0)
  1927. result = delta_negative(self);
  1928. else
  1929. result = delta_positive(self);
  1930. return result;
  1931. }
  1932. static PyObject *
  1933. delta_subtract(PyObject *left, PyObject *right)
  1934. {
  1935. PyObject *result = Py_NotImplemented;
  1936. if (PyDelta_Check(left) && PyDelta_Check(right)) {
  1937. /* delta - delta */
  1938. /* The C-level additions can't overflow because of the
  1939. * invariant bounds.
  1940. */
  1941. int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
  1942. int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
  1943. int microseconds = GET_TD_MICROSECONDS(left) -
  1944. GET_TD_MICROSECONDS(right);
  1945. result = new_delta(days, seconds, microseconds, 1);
  1946. }
  1947. if (result == Py_NotImplemented)
  1948. Py_INCREF(result);
  1949. return result;
  1950. }
  1951. static int
  1952. delta_cmp(PyObject *self, PyObject *other)
  1953. {
  1954. int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
  1955. if (diff == 0) {
  1956. diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
  1957. if (diff == 0)
  1958. diff = GET_TD_MICROSECONDS(self) -
  1959. GET_TD_MICROSECONDS(other);
  1960. }
  1961. return diff;
  1962. }
  1963. static PyObject *
  1964. delta_richcompare(PyObject *self, PyObject *other, int op)
  1965. {
  1966. if (PyDelta_Check(other)) {
  1967. int diff = delta_cmp(self, other);
  1968. return diff_to_bool(diff, op);
  1969. }
  1970. else {
  1971. Py_RETURN_NOTIMPLEMENTED;
  1972. }
  1973. }
  1974. static PyObject *delta_getstate(PyDateTime_Delta *self);
  1975. static Py_hash_t
  1976. delta_hash(PyDateTime_Delta *self)
  1977. {
  1978. if (self->hashcode == -1) {
  1979. PyObject *temp = delta_getstate(self);
  1980. if (temp != NULL) {
  1981. self->hashcode = PyObject_Hash(temp);
  1982. Py_DECREF(temp);
  1983. }
  1984. }
  1985. return self->hashcode;
  1986. }
  1987. static PyObject *
  1988. delta_multiply(PyObject *left, PyObject *right)
  1989. {
  1990. PyObject *result = Py_NotImplemented;
  1991. if (PyDelta_Check(left)) {
  1992. /* delta * ??? */
  1993. if (PyLong_Check(right))
  1994. result = multiply_int_timedelta(right,
  1995. (PyDateTime_Delta *) left);
  1996. else if (PyFloat_Check(right))
  1997. result = multiply_truedivide_timedelta_float(
  1998. (PyDateTime_Delta *) left, right, 0);
  1999. }
  2000. else if (PyLong_Check(left))
  2001. result = multiply_int_timedelta(left,
  2002. (PyDateTime_Delta *) right);
  2003. else if (PyFloat_Check(left))
  2004. result = multiply_truedivide_timedelta_float(
  2005. (PyDateTime_Delta *) right, left, 0);
  2006. if (result == Py_NotImplemented)
  2007. Py_INCREF(result);
  2008. return result;
  2009. }
  2010. static PyObject *
  2011. delta_divide(PyObject *left, PyObject *right)
  2012. {
  2013. PyObject *result = Py_NotImplemented;
  2014. if (PyDelta_Check(left)) {
  2015. /* delta * ??? */
  2016. if (PyLong_Check(right))
  2017. result = divide_timedelta_int(
  2018. (PyDateTime_Delta *)left,
  2019. right);
  2020. else if (PyDelta_Check(right))
  2021. result = divide_timedelta_timedelta(
  2022. (PyDateTime_Delta *)left,
  2023. (PyDateTime_Delta *)right);
  2024. }
  2025. if (result == Py_NotImplemented)
  2026. Py_INCREF(result);
  2027. return result;
  2028. }
  2029. static PyObject *
  2030. delta_truedivide(PyObject *left, PyObject *right)
  2031. {
  2032. PyObject *result = Py_NotImplemented;
  2033. if (PyDelta_Check(left)) {
  2034. if (PyDelta_Check(right))
  2035. result = truedivide_timedelta_timedelta(
  2036. (PyDateTime_Delta *)left,
  2037. (PyDateTime_Delta *)right);
  2038. else if (PyFloat_Check(right))
  2039. result = multiply_truedivide_timedelta_float(
  2040. (PyDateTime_Delta *)left, right, 1);
  2041. else if (PyLong_Check(right))
  2042. result = truedivide_timedelta_int(
  2043. (PyDateTime_Delta *)left, right);
  2044. }
  2045. if (result == Py_NotImplemented)
  2046. Py_INCREF(result);
  2047. return result;
  2048. }
  2049. static PyObject *
  2050. delta_remainder(PyObject *left, PyObject *right)
  2051. {
  2052. PyObject *pyus_left;
  2053. PyObject *pyus_right;
  2054. PyObject *pyus_remainder;
  2055. PyObject *remainder;
  2056. if (!PyDelta_Check(left) || !PyDelta_Check(right))
  2057. Py_RETURN_NOTIMPLEMENTED;
  2058. pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
  2059. if (pyus_left == NULL)
  2060. return NULL;
  2061. pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
  2062. if (pyus_right == NULL) {
  2063. Py_DECREF(pyus_left);
  2064. return NULL;
  2065. }
  2066. pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
  2067. Py_DECREF(pyus_left);
  2068. Py_DECREF(pyus_right);
  2069. if (pyus_remainder == NULL)
  2070. return NULL;
  2071. remainder = microseconds_to_delta(pyus_remainder);
  2072. Py_DECREF(pyus_remainder);
  2073. if (remainder == NULL)
  2074. return NULL;
  2075. return remainder;
  2076. }
  2077. static PyObject *
  2078. delta_divmod(PyObject *left, PyObject *right)
  2079. {
  2080. PyObject *pyus_left;
  2081. PyObject *pyus_right;
  2082. PyObject *divmod;
  2083. PyObject *delta;
  2084. PyObject *result;
  2085. if (!PyDelta_Check(left) || !PyDelta_Check(right))
  2086. Py_RETURN_NOTIMPLEMENTED;
  2087. pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
  2088. if (pyus_left == NULL)
  2089. return NULL;
  2090. pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
  2091. if (pyus_right == NULL) {
  2092. Py_DECREF(pyus_left);
  2093. return NULL;
  2094. }
  2095. divmod = checked_divmod(pyus_left, pyus_right);
  2096. Py_DECREF(pyus_left);
  2097. Py_DECREF(pyus_right);
  2098. if (divmod == NULL)
  2099. return NULL;
  2100. delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
  2101. if (delta == NULL) {
  2102. Py_DECREF(divmod);
  2103. return NULL;
  2104. }
  2105. result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
  2106. Py_DECREF(delta);
  2107. Py_DECREF(divmod);
  2108. return result;
  2109. }
  2110. /* Fold in the value of the tag ("seconds", "weeks", etc) component of a
  2111. * timedelta constructor. sofar is the # of microseconds accounted for
  2112. * so far, and there are factor microseconds per current unit, the number
  2113. * of which is given by num. num * factor is added to sofar in a
  2114. * numerically careful way, and that's the result. Any fractional
  2115. * microseconds left over (this can happen if num is a float type) are
  2116. * added into *leftover.
  2117. * Note that there are many ways this can give an error (NULL) return.
  2118. */
  2119. static PyObject *
  2120. accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
  2121. double *leftover)
  2122. {
  2123. PyObject *prod;
  2124. PyObject *sum;
  2125. assert(num != NULL);
  2126. if (PyLong_Check(num)) {
  2127. prod = PyNumber_Multiply(num, factor);
  2128. if (prod == NULL)
  2129. return NULL;
  2130. sum = PyNumber_Add(sofar, prod);
  2131. Py_DECREF(prod);
  2132. return sum;
  2133. }
  2134. if (PyFloat_Check(num)) {
  2135. double dnum;
  2136. double fracpart;
  2137. double intpart;
  2138. PyObject *x;
  2139. PyObject *y;
  2140. /* The Plan: decompose num into an integer part and a
  2141. * fractional part, num = intpart + fracpart.
  2142. * Then num * factor ==
  2143. * intpart * factor + fracpart * factor
  2144. * and the LHS can be computed exactly in long arithmetic.
  2145. * The RHS is again broken into an int part and frac part.
  2146. * and the frac part is added into *leftover.
  2147. */
  2148. dnum = PyFloat_AsDouble(num);
  2149. if (dnum == -1.0 && PyErr_Occurred())
  2150. return NULL;
  2151. fracpart = modf(dnum, &intpart);
  2152. x = PyLong_FromDouble(intpart);
  2153. if (x == NULL)
  2154. return NULL;
  2155. prod = PyNumber_Multiply(x, factor);
  2156. Py_DECREF(x);
  2157. if (prod == NULL)
  2158. return NULL;
  2159. sum = PyNumber_Add(sofar, prod);
  2160. Py_DECREF(prod);
  2161. if (sum == NULL)
  2162. return NULL;
  2163. if (fracpart == 0.0)
  2164. return sum;
  2165. /* So far we've lost no information. Dealing with the
  2166. * fractional part requires float arithmetic, and may
  2167. * lose a little info.
  2168. */
  2169. assert(PyLong_CheckExact(factor));
  2170. dnum = PyLong_AsDouble(factor);
  2171. dnum *= fracpart;
  2172. fracpart = modf(dnum, &intpart);
  2173. x = PyLong_FromDouble(intpart);
  2174. if (x == NULL) {
  2175. Py_DECREF(sum);
  2176. return NULL;
  2177. }
  2178. y = PyNumber_Add(sum, x);
  2179. Py_DECREF(sum);
  2180. Py_DECREF(x);
  2181. *leftover += fracpart;
  2182. return y;
  2183. }
  2184. PyErr_Format(PyExc_TypeError,
  2185. "unsupported type for timedelta %s component: %s",
  2186. tag, Py_TYPE(num)->tp_name);
  2187. return NULL;
  2188. }
  2189. static PyObject *
  2190. delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  2191. {
  2192. PyObject *self = NULL;
  2193. /* Argument objects. */
  2194. PyObject *day = NULL;
  2195. PyObject *second = NULL;
  2196. PyObject *us = NULL;
  2197. PyObject *ms = NULL;
  2198. PyObject *minute = NULL;
  2199. PyObject *hour = NULL;
  2200. PyObject *week = NULL;
  2201. PyObject *x = NULL; /* running sum of microseconds */
  2202. PyObject *y = NULL; /* temp sum of microseconds */
  2203. double leftover_us = 0.0;
  2204. static char *keywords[] = {
  2205. "days", "seconds", "microseconds", "milliseconds",
  2206. "minutes", "hours", "weeks", NULL
  2207. };
  2208. if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
  2209. keywords,
  2210. &day, &second, &us,
  2211. &ms, &minute, &hour, &week) == 0)
  2212. goto Done;
  2213. x = PyLong_FromLong(0);
  2214. if (x == NULL)
  2215. goto Done;
  2216. #define CLEANUP \
  2217. Py_DECREF(x); \
  2218. x = y; \
  2219. if (x == NULL) \
  2220. goto Done
  2221. if (us) {
  2222. y = accum("microseconds", x, us, _PyLong_GetOne(), &leftover_us);
  2223. CLEANUP;
  2224. }
  2225. if (ms) {
  2226. y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
  2227. CLEANUP;
  2228. }
  2229. if (second) {
  2230. y = accum("seconds", x, second, us_per_second, &leftover_us);
  2231. CLEANUP;
  2232. }
  2233. if (minute) {
  2234. y = accum("minutes", x, minute, us_per_minute, &leftover_us);
  2235. CLEANUP;
  2236. }
  2237. if (hour) {
  2238. y = accum("hours", x, hour, us_per_hour, &leftover_us);
  2239. CLEANUP;
  2240. }
  2241. if (day) {
  2242. y = accum("days", x, day, us_per_day, &leftover_us);
  2243. CLEANUP;
  2244. }
  2245. if (week) {
  2246. y = accum("weeks", x, week, us_per_week, &leftover_us);
  2247. CLEANUP;
  2248. }
  2249. if (leftover_us) {
  2250. /* Round to nearest whole # of us, and add into x. */
  2251. double whole_us = round(leftover_us);
  2252. int x_is_odd;
  2253. PyObject *temp;
  2254. if (fabs(whole_us - leftover_us) == 0.5) {
  2255. /* We're exactly halfway between two integers. In order
  2256. * to do round-half-to-even, we must determine whether x
  2257. * is odd. Note that x is odd when it's last bit is 1. The
  2258. * code below uses bitwise and operation to check the last
  2259. * bit. */
  2260. temp = PyNumber_And(x, _PyLong_GetOne()); /* temp <- x & 1 */
  2261. if (temp == NULL) {
  2262. Py_DECREF(x);
  2263. goto Done;
  2264. }
  2265. x_is_odd = PyObject_IsTrue(temp);
  2266. Py_DECREF(temp);
  2267. if (x_is_odd == -1) {
  2268. Py_DECREF(x);
  2269. goto Done;
  2270. }
  2271. whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
  2272. }
  2273. temp = PyLong_FromLong((long)whole_us);
  2274. if (temp == NULL) {
  2275. Py_DECREF(x);
  2276. goto Done;
  2277. }
  2278. y = PyNumber_Add(x, temp);
  2279. Py_DECREF(temp);
  2280. CLEANUP;
  2281. }
  2282. self = microseconds_to_delta_ex(x, type);
  2283. Py_DECREF(x);
  2284. Done:
  2285. return self;
  2286. #undef CLEANUP
  2287. }
  2288. static int
  2289. delta_bool(PyDateTime_Delta *self)
  2290. {
  2291. return (GET_TD_DAYS(self) != 0
  2292. || GET_TD_SECONDS(self) != 0
  2293. || GET_TD_MICROSECONDS(self) != 0);
  2294. }
  2295. static PyObject *
  2296. delta_repr(PyDateTime_Delta *self)
  2297. {
  2298. PyObject *args = PyUnicode_FromString("");
  2299. if (args == NULL) {
  2300. return NULL;
  2301. }
  2302. const char *sep = "";
  2303. if (GET_TD_DAYS(self) != 0) {
  2304. Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
  2305. if (args == NULL) {
  2306. return NULL;
  2307. }
  2308. sep = ", ";
  2309. }
  2310. if (GET_TD_SECONDS(self) != 0) {
  2311. Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
  2312. GET_TD_SECONDS(self)));
  2313. if (args == NULL) {
  2314. return NULL;
  2315. }
  2316. sep = ", ";
  2317. }
  2318. if (GET_TD_MICROSECONDS(self) != 0) {
  2319. Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
  2320. GET_TD_MICROSECONDS(self)));
  2321. if (args == NULL) {
  2322. return NULL;
  2323. }
  2324. }
  2325. if (PyUnicode_GET_LENGTH(args) == 0) {
  2326. Py_SETREF(args, PyUnicode_FromString("0"));
  2327. if (args == NULL) {
  2328. return NULL;
  2329. }
  2330. }
  2331. PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
  2332. args);
  2333. Py_DECREF(args);
  2334. return repr;
  2335. }
  2336. static PyObject *
  2337. delta_str(PyDateTime_Delta *self)
  2338. {
  2339. int us = GET_TD_MICROSECONDS(self);
  2340. int seconds = GET_TD_SECONDS(self);
  2341. int minutes = divmod(seconds, 60, &seconds);
  2342. int hours = divmod(minutes, 60, &minutes);
  2343. int days = GET_TD_DAYS(self);
  2344. if (days) {
  2345. if (us)
  2346. return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
  2347. days, (days == 1 || days == -1) ? "" : "s",
  2348. hours, minutes, seconds, us);
  2349. else
  2350. return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
  2351. days, (days == 1 || days == -1) ? "" : "s",
  2352. hours, minutes, seconds);
  2353. } else {
  2354. if (us)
  2355. return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
  2356. hours, minutes, seconds, us);
  2357. else
  2358. return PyUnicode_FromFormat("%d:%02d:%02d",
  2359. hours, minutes, seconds);
  2360. }
  2361. }
  2362. /* Pickle support, a simple use of __reduce__. */
  2363. /* __getstate__ isn't exposed */
  2364. static PyObject *
  2365. delta_getstate(PyDateTime_Delta *self)
  2366. {
  2367. return Py_BuildValue("iii", GET_TD_DAYS(self),
  2368. GET_TD_SECONDS(self),
  2369. GET_TD_MICROSECONDS(self));
  2370. }
  2371. static PyObject *
  2372. delta_total_seconds(PyObject *self, PyObject *Py_UNUSED(ignored))
  2373. {
  2374. PyObject *total_seconds;
  2375. PyObject *total_microseconds;
  2376. total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
  2377. if (total_microseconds == NULL)
  2378. return NULL;
  2379. total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
  2380. Py_DECREF(total_microseconds);
  2381. return total_seconds;
  2382. }
  2383. static PyObject *
  2384. delta_reduce(PyDateTime_Delta* self, PyObject *Py_UNUSED(ignored))
  2385. {
  2386. return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
  2387. }
  2388. #define OFFSET(field) offsetof(PyDateTime_Delta, field)
  2389. static PyMemberDef delta_members[] = {
  2390. {"days", T_INT, OFFSET(days), READONLY,
  2391. PyDoc_STR("Number of days.")},
  2392. {"seconds", T_INT, OFFSET(seconds), READONLY,
  2393. PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
  2394. {"microseconds", T_INT, OFFSET(microseconds), READONLY,
  2395. PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
  2396. {NULL}
  2397. };
  2398. static PyMethodDef delta_methods[] = {
  2399. {"total_seconds", delta_total_seconds, METH_NOARGS,
  2400. PyDoc_STR("Total seconds in the duration.")},
  2401. {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
  2402. PyDoc_STR("__reduce__() -> (cls, state)")},
  2403. {NULL, NULL},
  2404. };
  2405. static const char delta_doc[] =
  2406. PyDoc_STR("Difference between two datetime values.\n\n"
  2407. "timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, "
  2408. "minutes=0, hours=0, weeks=0)\n\n"
  2409. "All arguments are optional and default to 0.\n"
  2410. "Arguments may be integers or floats, and may be positive or negative.");
  2411. static PyNumberMethods delta_as_number = {
  2412. delta_add, /* nb_add */
  2413. delta_subtract, /* nb_subtract */
  2414. delta_multiply, /* nb_multiply */
  2415. delta_remainder, /* nb_remainder */
  2416. delta_divmod, /* nb_divmod */
  2417. 0, /* nb_power */
  2418. (unaryfunc)delta_negative, /* nb_negative */
  2419. (unaryfunc)delta_positive, /* nb_positive */
  2420. (unaryfunc)delta_abs, /* nb_absolute */
  2421. (inquiry)delta_bool, /* nb_bool */
  2422. 0, /*nb_invert*/
  2423. 0, /*nb_lshift*/
  2424. 0, /*nb_rshift*/
  2425. 0, /*nb_and*/
  2426. 0, /*nb_xor*/
  2427. 0, /*nb_or*/
  2428. 0, /*nb_int*/
  2429. 0, /*nb_reserved*/
  2430. 0, /*nb_float*/
  2431. 0, /*nb_inplace_add*/
  2432. 0, /*nb_inplace_subtract*/
  2433. 0, /*nb_inplace_multiply*/
  2434. 0, /*nb_inplace_remainder*/
  2435. 0, /*nb_inplace_power*/
  2436. 0, /*nb_inplace_lshift*/
  2437. 0, /*nb_inplace_rshift*/
  2438. 0, /*nb_inplace_and*/
  2439. 0, /*nb_inplace_xor*/
  2440. 0, /*nb_inplace_or*/
  2441. delta_divide, /* nb_floor_divide */
  2442. delta_truedivide, /* nb_true_divide */
  2443. 0, /* nb_inplace_floor_divide */
  2444. 0, /* nb_inplace_true_divide */
  2445. };
  2446. static PyTypeObject PyDateTime_DeltaType = {
  2447. PyVarObject_HEAD_INIT(NULL, 0)
  2448. "datetime.timedelta", /* tp_name */
  2449. sizeof(PyDateTime_Delta), /* tp_basicsize */
  2450. 0, /* tp_itemsize */
  2451. 0, /* tp_dealloc */
  2452. 0, /* tp_vectorcall_offset */
  2453. 0, /* tp_getattr */
  2454. 0, /* tp_setattr */
  2455. 0, /* tp_as_async */
  2456. (reprfunc)delta_repr, /* tp_repr */
  2457. &delta_as_number, /* tp_as_number */
  2458. 0, /* tp_as_sequence */
  2459. 0, /* tp_as_mapping */
  2460. (hashfunc)delta_hash, /* tp_hash */
  2461. 0, /* tp_call */
  2462. (reprfunc)delta_str, /* tp_str */
  2463. PyObject_GenericGetAttr, /* tp_getattro */
  2464. 0, /* tp_setattro */
  2465. 0, /* tp_as_buffer */
  2466. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  2467. delta_doc, /* tp_doc */
  2468. 0, /* tp_traverse */
  2469. 0, /* tp_clear */
  2470. delta_richcompare, /* tp_richcompare */
  2471. 0, /* tp_weaklistoffset */
  2472. 0, /* tp_iter */
  2473. 0, /* tp_iternext */
  2474. delta_methods, /* tp_methods */
  2475. delta_members, /* tp_members */
  2476. 0, /* tp_getset */
  2477. 0, /* tp_base */
  2478. 0, /* tp_dict */
  2479. 0, /* tp_descr_get */
  2480. 0, /* tp_descr_set */
  2481. 0, /* tp_dictoffset */
  2482. 0, /* tp_init */
  2483. 0, /* tp_alloc */
  2484. delta_new, /* tp_new */
  2485. 0, /* tp_free */
  2486. };
  2487. /*
  2488. * PyDateTime_Date implementation.
  2489. */
  2490. /* Accessor properties. */
  2491. static PyObject *
  2492. date_year(PyDateTime_Date *self, void *unused)
  2493. {
  2494. return PyLong_FromLong(GET_YEAR(self));
  2495. }
  2496. static PyObject *
  2497. date_month(PyDateTime_Date *self, void *unused)
  2498. {
  2499. return PyLong_FromLong(GET_MONTH(self));
  2500. }
  2501. static PyObject *
  2502. date_day(PyDateTime_Date *self, void *unused)
  2503. {
  2504. return PyLong_FromLong(GET_DAY(self));
  2505. }
  2506. static PyGetSetDef date_getset[] = {
  2507. {"year", (getter)date_year},
  2508. {"month", (getter)date_month},
  2509. {"day", (getter)date_day},
  2510. {NULL}
  2511. };
  2512. /* Constructors. */
  2513. static char *date_kws[] = {"year", "month", "day", NULL};
  2514. static PyObject *
  2515. date_from_pickle(PyTypeObject *type, PyObject *state)
  2516. {
  2517. PyDateTime_Date *me;
  2518. me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
  2519. if (me != NULL) {
  2520. const char *pdata = PyBytes_AS_STRING(state);
  2521. memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
  2522. me->hashcode = -1;
  2523. }
  2524. return (PyObject *)me;
  2525. }
  2526. static PyObject *
  2527. date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  2528. {
  2529. PyObject *self = NULL;
  2530. int year;
  2531. int month;
  2532. int day;
  2533. /* Check for invocation from pickle with __getstate__ state */
  2534. if (PyTuple_GET_SIZE(args) == 1) {
  2535. PyObject *state = PyTuple_GET_ITEM(args, 0);
  2536. if (PyBytes_Check(state)) {
  2537. if (PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
  2538. MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
  2539. {
  2540. return date_from_pickle(type, state);
  2541. }
  2542. }
  2543. else if (PyUnicode_Check(state)) {
  2544. if (PyUnicode_READY(state)) {
  2545. return NULL;
  2546. }
  2547. if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATE_DATASIZE &&
  2548. MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2)))
  2549. {
  2550. state = PyUnicode_AsLatin1String(state);
  2551. if (state == NULL) {
  2552. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
  2553. /* More informative error message. */
  2554. PyErr_SetString(PyExc_ValueError,
  2555. "Failed to encode latin1 string when unpickling "
  2556. "a date object. "
  2557. "pickle.load(data, encoding='latin1') is assumed.");
  2558. }
  2559. return NULL;
  2560. }
  2561. self = date_from_pickle(type, state);
  2562. Py_DECREF(state);
  2563. return self;
  2564. }
  2565. }
  2566. }
  2567. if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
  2568. &year, &month, &day)) {
  2569. self = new_date_ex(year, month, day, type);
  2570. }
  2571. return self;
  2572. }
  2573. static PyObject *
  2574. date_fromtimestamp(PyObject *cls, PyObject *obj)
  2575. {
  2576. struct tm tm;
  2577. time_t t;
  2578. if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
  2579. return NULL;
  2580. if (_PyTime_localtime(t, &tm) != 0)
  2581. return NULL;
  2582. return new_date_subclass_ex(tm.tm_year + 1900,
  2583. tm.tm_mon + 1,
  2584. tm.tm_mday,
  2585. cls);
  2586. }
  2587. /* Return new date from current time.
  2588. * We say this is equivalent to fromtimestamp(time.time()), and the
  2589. * only way to be sure of that is to *call* time.time(). That's not
  2590. * generally the same as calling C's time.
  2591. */
  2592. static PyObject *
  2593. date_today(PyObject *cls, PyObject *dummy)
  2594. {
  2595. PyObject *time;
  2596. PyObject *result;
  2597. time = time_time();
  2598. if (time == NULL)
  2599. return NULL;
  2600. /* Note well: today() is a class method, so this may not call
  2601. * date.fromtimestamp. For example, it may call
  2602. * datetime.fromtimestamp. That's why we need all the accuracy
  2603. * time.time() delivers; if someone were gonzo about optimization,
  2604. * date.today() could get away with plain C time().
  2605. */
  2606. result = PyObject_CallMethodOneArg(cls, &_Py_ID(fromtimestamp), time);
  2607. Py_DECREF(time);
  2608. return result;
  2609. }
  2610. /*[clinic input]
  2611. @classmethod
  2612. datetime.date.fromtimestamp
  2613. timestamp: object
  2614. /
  2615. Create a date from a POSIX timestamp.
  2616. The timestamp is a number, e.g. created via time.time(), that is interpreted
  2617. as local time.
  2618. [clinic start generated code]*/
  2619. static PyObject *
  2620. datetime_date_fromtimestamp(PyTypeObject *type, PyObject *timestamp)
  2621. /*[clinic end generated code: output=fd045fda58168869 input=eabb3fe7f40491fe]*/
  2622. {
  2623. return date_fromtimestamp((PyObject *) type, timestamp);
  2624. }
  2625. /* bpo-36025: This is a wrapper for API compatibility with the public C API,
  2626. * which expects a function that takes an *args tuple, whereas the argument
  2627. * clinic generates code that takes METH_O.
  2628. */
  2629. static PyObject *
  2630. datetime_date_fromtimestamp_capi(PyObject *cls, PyObject *args)
  2631. {
  2632. PyObject *timestamp;
  2633. PyObject *result = NULL;
  2634. if (PyArg_UnpackTuple(args, "fromtimestamp", 1, 1, &timestamp)) {
  2635. result = date_fromtimestamp(cls, timestamp);
  2636. }
  2637. return result;
  2638. }
  2639. /* Return new date from proleptic Gregorian ordinal. Raises ValueError if
  2640. * the ordinal is out of range.
  2641. */
  2642. static PyObject *
  2643. date_fromordinal(PyObject *cls, PyObject *args)
  2644. {
  2645. PyObject *result = NULL;
  2646. int ordinal;
  2647. if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
  2648. int year;
  2649. int month;
  2650. int day;
  2651. if (ordinal < 1)
  2652. PyErr_SetString(PyExc_ValueError, "ordinal must be "
  2653. ">= 1");
  2654. else {
  2655. ord_to_ymd(ordinal, &year, &month, &day);
  2656. result = new_date_subclass_ex(year, month, day, cls);
  2657. }
  2658. }
  2659. return result;
  2660. }
  2661. /* Return the new date from a string as generated by date.isoformat() */
  2662. static PyObject *
  2663. date_fromisoformat(PyObject *cls, PyObject *dtstr)
  2664. {
  2665. assert(dtstr != NULL);
  2666. if (!PyUnicode_Check(dtstr)) {
  2667. PyErr_SetString(PyExc_TypeError,
  2668. "fromisoformat: argument must be str");
  2669. return NULL;
  2670. }
  2671. Py_ssize_t len;
  2672. const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr, &len);
  2673. if (dt_ptr == NULL) {
  2674. goto invalid_string_error;
  2675. }
  2676. int year = 0, month = 0, day = 0;
  2677. int rv;
  2678. if (len == 7 || len == 8 || len == 10) {
  2679. rv = parse_isoformat_date(dt_ptr, len, &year, &month, &day);
  2680. }
  2681. else {
  2682. rv = -1;
  2683. }
  2684. if (rv < 0) {
  2685. goto invalid_string_error;
  2686. }
  2687. return new_date_subclass_ex(year, month, day, cls);
  2688. invalid_string_error:
  2689. PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
  2690. return NULL;
  2691. }
  2692. static PyObject *
  2693. date_fromisocalendar(PyObject *cls, PyObject *args, PyObject *kw)
  2694. {
  2695. static char *keywords[] = {
  2696. "year", "week", "day", NULL
  2697. };
  2698. int year, week, day;
  2699. if (PyArg_ParseTupleAndKeywords(args, kw, "iii:fromisocalendar",
  2700. keywords,
  2701. &year, &week, &day) == 0) {
  2702. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  2703. PyErr_Format(PyExc_ValueError,
  2704. "ISO calendar component out of range");
  2705. }
  2706. return NULL;
  2707. }
  2708. int month;
  2709. int rv = iso_to_ymd(year, week, day, &year, &month, &day);
  2710. if (rv == -4) {
  2711. PyErr_Format(PyExc_ValueError, "Year is out of range: %d", year);
  2712. return NULL;
  2713. }
  2714. if (rv == -2) {
  2715. PyErr_Format(PyExc_ValueError, "Invalid week: %d", week);
  2716. return NULL;
  2717. }
  2718. if (rv == -3) {
  2719. PyErr_Format(PyExc_ValueError, "Invalid day: %d (range is [1, 7])",
  2720. day);
  2721. return NULL;
  2722. }
  2723. return new_date_subclass_ex(year, month, day, cls);
  2724. }
  2725. /*
  2726. * Date arithmetic.
  2727. */
  2728. /* date + timedelta -> date. If arg negate is true, subtract the timedelta
  2729. * instead.
  2730. */
  2731. static PyObject *
  2732. add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
  2733. {
  2734. PyObject *result = NULL;
  2735. int year = GET_YEAR(date);
  2736. int month = GET_MONTH(date);
  2737. int deltadays = GET_TD_DAYS(delta);
  2738. /* C-level overflow is impossible because |deltadays| < 1e9. */
  2739. int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
  2740. if (normalize_date(&year, &month, &day) >= 0)
  2741. result = new_date_subclass_ex(year, month, day,
  2742. (PyObject* )Py_TYPE(date));
  2743. return result;
  2744. }
  2745. static PyObject *
  2746. date_add(PyObject *left, PyObject *right)
  2747. {
  2748. if (PyDateTime_Check(left) || PyDateTime_Check(right))
  2749. Py_RETURN_NOTIMPLEMENTED;
  2750. if (PyDate_Check(left)) {
  2751. /* date + ??? */
  2752. if (PyDelta_Check(right))
  2753. /* date + delta */
  2754. return add_date_timedelta((PyDateTime_Date *) left,
  2755. (PyDateTime_Delta *) right,
  2756. 0);
  2757. }
  2758. else {
  2759. /* ??? + date
  2760. * 'right' must be one of us, or we wouldn't have been called
  2761. */
  2762. if (PyDelta_Check(left))
  2763. /* delta + date */
  2764. return add_date_timedelta((PyDateTime_Date *) right,
  2765. (PyDateTime_Delta *) left,
  2766. 0);
  2767. }
  2768. Py_RETURN_NOTIMPLEMENTED;
  2769. }
  2770. static PyObject *
  2771. date_subtract(PyObject *left, PyObject *right)
  2772. {
  2773. if (PyDateTime_Check(left) || PyDateTime_Check(right))
  2774. Py_RETURN_NOTIMPLEMENTED;
  2775. if (PyDate_Check(left)) {
  2776. if (PyDate_Check(right)) {
  2777. /* date - date */
  2778. int left_ord = ymd_to_ord(GET_YEAR(left),
  2779. GET_MONTH(left),
  2780. GET_DAY(left));
  2781. int right_ord = ymd_to_ord(GET_YEAR(right),
  2782. GET_MONTH(right),
  2783. GET_DAY(right));
  2784. return new_delta(left_ord - right_ord, 0, 0, 0);
  2785. }
  2786. if (PyDelta_Check(right)) {
  2787. /* date - delta */
  2788. return add_date_timedelta((PyDateTime_Date *) left,
  2789. (PyDateTime_Delta *) right,
  2790. 1);
  2791. }
  2792. }
  2793. Py_RETURN_NOTIMPLEMENTED;
  2794. }
  2795. /* Various ways to turn a date into a string. */
  2796. static PyObject *
  2797. date_repr(PyDateTime_Date *self)
  2798. {
  2799. return PyUnicode_FromFormat("%s(%d, %d, %d)",
  2800. Py_TYPE(self)->tp_name,
  2801. GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2802. }
  2803. static PyObject *
  2804. date_isoformat(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  2805. {
  2806. return PyUnicode_FromFormat("%04d-%02d-%02d",
  2807. GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2808. }
  2809. /* str() calls the appropriate isoformat() method. */
  2810. static PyObject *
  2811. date_str(PyDateTime_Date *self)
  2812. {
  2813. return PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(isoformat));
  2814. }
  2815. static PyObject *
  2816. date_ctime(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  2817. {
  2818. return format_ctime(self, 0, 0, 0);
  2819. }
  2820. static PyObject *
  2821. date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
  2822. {
  2823. /* This method can be inherited, and needs to call the
  2824. * timetuple() method appropriate to self's class.
  2825. */
  2826. PyObject *result;
  2827. PyObject *tuple;
  2828. PyObject *format;
  2829. static char *keywords[] = {"format", NULL};
  2830. if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
  2831. &format))
  2832. return NULL;
  2833. tuple = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(timetuple));
  2834. if (tuple == NULL)
  2835. return NULL;
  2836. result = wrap_strftime((PyObject *)self, format, tuple,
  2837. (PyObject *)self);
  2838. Py_DECREF(tuple);
  2839. return result;
  2840. }
  2841. static PyObject *
  2842. date_format(PyDateTime_Date *self, PyObject *args)
  2843. {
  2844. PyObject *format;
  2845. if (!PyArg_ParseTuple(args, "U:__format__", &format))
  2846. return NULL;
  2847. /* if the format is zero length, return str(self) */
  2848. if (PyUnicode_GetLength(format) == 0)
  2849. return PyObject_Str((PyObject *)self);
  2850. return PyObject_CallMethodOneArg((PyObject *)self, &_Py_ID(strftime),
  2851. format);
  2852. }
  2853. /* ISO methods. */
  2854. static PyObject *
  2855. date_isoweekday(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  2856. {
  2857. int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2858. return PyLong_FromLong(dow + 1);
  2859. }
  2860. PyDoc_STRVAR(iso_calendar_date__doc__,
  2861. "The result of date.isocalendar() or datetime.isocalendar()\n\n\
  2862. This object may be accessed either as a tuple of\n\
  2863. ((year, week, weekday)\n\
  2864. or via the object attributes as named in the above tuple.");
  2865. typedef struct {
  2866. PyTupleObject tuple;
  2867. } PyDateTime_IsoCalendarDate;
  2868. static PyObject *
  2869. iso_calendar_date_repr(PyDateTime_IsoCalendarDate *self)
  2870. {
  2871. PyObject* year = PyTuple_GetItem((PyObject *)self, 0);
  2872. if (year == NULL) {
  2873. return NULL;
  2874. }
  2875. PyObject* week = PyTuple_GetItem((PyObject *)self, 1);
  2876. if (week == NULL) {
  2877. return NULL;
  2878. }
  2879. PyObject* weekday = PyTuple_GetItem((PyObject *)self, 2);
  2880. if (weekday == NULL) {
  2881. return NULL;
  2882. }
  2883. return PyUnicode_FromFormat("%.200s(year=%S, week=%S, weekday=%S)",
  2884. Py_TYPE(self)->tp_name, year, week, weekday);
  2885. }
  2886. static PyObject *
  2887. iso_calendar_date_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
  2888. {
  2889. // Construct the tuple that this reduces to
  2890. PyObject * reduce_tuple = Py_BuildValue(
  2891. "O((OOO))", &PyTuple_Type,
  2892. PyTuple_GET_ITEM(self, 0),
  2893. PyTuple_GET_ITEM(self, 1),
  2894. PyTuple_GET_ITEM(self, 2)
  2895. );
  2896. return reduce_tuple;
  2897. }
  2898. static PyObject *
  2899. iso_calendar_date_year(PyDateTime_IsoCalendarDate *self, void *unused)
  2900. {
  2901. PyObject *year = PyTuple_GetItem((PyObject *)self, 0);
  2902. if (year == NULL) {
  2903. return NULL;
  2904. }
  2905. return Py_NewRef(year);
  2906. }
  2907. static PyObject *
  2908. iso_calendar_date_week(PyDateTime_IsoCalendarDate *self, void *unused)
  2909. {
  2910. PyObject *week = PyTuple_GetItem((PyObject *)self, 1);
  2911. if (week == NULL) {
  2912. return NULL;
  2913. }
  2914. return Py_NewRef(week);
  2915. }
  2916. static PyObject *
  2917. iso_calendar_date_weekday(PyDateTime_IsoCalendarDate *self, void *unused)
  2918. {
  2919. PyObject *weekday = PyTuple_GetItem((PyObject *)self, 2);
  2920. if (weekday == NULL) {
  2921. return NULL;
  2922. }
  2923. return Py_NewRef(weekday);
  2924. }
  2925. static PyGetSetDef iso_calendar_date_getset[] = {
  2926. {"year", (getter)iso_calendar_date_year},
  2927. {"week", (getter)iso_calendar_date_week},
  2928. {"weekday", (getter)iso_calendar_date_weekday},
  2929. {NULL}
  2930. };
  2931. static PyMethodDef iso_calendar_date_methods[] = {
  2932. {"__reduce__", (PyCFunction)iso_calendar_date_reduce, METH_NOARGS,
  2933. PyDoc_STR("__reduce__() -> (cls, state)")},
  2934. {NULL, NULL},
  2935. };
  2936. static PyTypeObject PyDateTime_IsoCalendarDateType = {
  2937. PyVarObject_HEAD_INIT(NULL, 0)
  2938. .tp_name = "datetime.IsoCalendarDate",
  2939. .tp_basicsize = sizeof(PyDateTime_IsoCalendarDate),
  2940. .tp_repr = (reprfunc) iso_calendar_date_repr,
  2941. .tp_flags = Py_TPFLAGS_DEFAULT,
  2942. .tp_doc = iso_calendar_date__doc__,
  2943. .tp_methods = iso_calendar_date_methods,
  2944. .tp_getset = iso_calendar_date_getset,
  2945. // .tp_base = &PyTuple_Type, // filled in PyInit__datetime
  2946. .tp_new = iso_calendar_date_new,
  2947. };
  2948. /*[clinic input]
  2949. @classmethod
  2950. datetime.IsoCalendarDate.__new__ as iso_calendar_date_new
  2951. year: int
  2952. week: int
  2953. weekday: int
  2954. [clinic start generated code]*/
  2955. static PyObject *
  2956. iso_calendar_date_new_impl(PyTypeObject *type, int year, int week,
  2957. int weekday)
  2958. /*[clinic end generated code: output=383d33d8dc7183a2 input=4f2c663c9d19c4ee]*/
  2959. {
  2960. PyDateTime_IsoCalendarDate *self;
  2961. self = (PyDateTime_IsoCalendarDate *) type->tp_alloc(type, 3);
  2962. if (self == NULL) {
  2963. return NULL;
  2964. }
  2965. PyTuple_SET_ITEM(self, 0, PyLong_FromLong(year));
  2966. PyTuple_SET_ITEM(self, 1, PyLong_FromLong(week));
  2967. PyTuple_SET_ITEM(self, 2, PyLong_FromLong(weekday));
  2968. return (PyObject *)self;
  2969. }
  2970. static PyObject *
  2971. date_isocalendar(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  2972. {
  2973. int year = GET_YEAR(self);
  2974. int week1_monday = iso_week1_monday(year);
  2975. int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
  2976. int week;
  2977. int day;
  2978. week = divmod(today - week1_monday, 7, &day);
  2979. if (week < 0) {
  2980. --year;
  2981. week1_monday = iso_week1_monday(year);
  2982. week = divmod(today - week1_monday, 7, &day);
  2983. }
  2984. else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
  2985. ++year;
  2986. week = 0;
  2987. }
  2988. PyObject* v = iso_calendar_date_new_impl(&PyDateTime_IsoCalendarDateType,
  2989. year, week + 1, day + 1);
  2990. if (v == NULL) {
  2991. return NULL;
  2992. }
  2993. return v;
  2994. }
  2995. /* Miscellaneous methods. */
  2996. static PyObject *
  2997. date_richcompare(PyObject *self, PyObject *other, int op)
  2998. {
  2999. if (PyDate_Check(other)) {
  3000. int diff = memcmp(((PyDateTime_Date *)self)->data,
  3001. ((PyDateTime_Date *)other)->data,
  3002. _PyDateTime_DATE_DATASIZE);
  3003. return diff_to_bool(diff, op);
  3004. }
  3005. else
  3006. Py_RETURN_NOTIMPLEMENTED;
  3007. }
  3008. static PyObject *
  3009. date_timetuple(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  3010. {
  3011. return build_struct_time(GET_YEAR(self),
  3012. GET_MONTH(self),
  3013. GET_DAY(self),
  3014. 0, 0, 0, -1);
  3015. }
  3016. static PyObject *
  3017. date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
  3018. {
  3019. PyObject *clone;
  3020. PyObject *tuple;
  3021. int year = GET_YEAR(self);
  3022. int month = GET_MONTH(self);
  3023. int day = GET_DAY(self);
  3024. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
  3025. &year, &month, &day))
  3026. return NULL;
  3027. tuple = Py_BuildValue("iii", year, month, day);
  3028. if (tuple == NULL)
  3029. return NULL;
  3030. clone = date_new(Py_TYPE(self), tuple, NULL);
  3031. Py_DECREF(tuple);
  3032. return clone;
  3033. }
  3034. static Py_hash_t
  3035. generic_hash(unsigned char *data, int len)
  3036. {
  3037. return _Py_HashBytes(data, len);
  3038. }
  3039. static PyObject *date_getstate(PyDateTime_Date *self);
  3040. static Py_hash_t
  3041. date_hash(PyDateTime_Date *self)
  3042. {
  3043. if (self->hashcode == -1) {
  3044. self->hashcode = generic_hash(
  3045. (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
  3046. }
  3047. return self->hashcode;
  3048. }
  3049. static PyObject *
  3050. date_toordinal(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  3051. {
  3052. return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
  3053. GET_DAY(self)));
  3054. }
  3055. static PyObject *
  3056. date_weekday(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
  3057. {
  3058. int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  3059. return PyLong_FromLong(dow);
  3060. }
  3061. /* Pickle support, a simple use of __reduce__. */
  3062. /* __getstate__ isn't exposed */
  3063. static PyObject *
  3064. date_getstate(PyDateTime_Date *self)
  3065. {
  3066. PyObject* field;
  3067. field = PyBytes_FromStringAndSize((char*)self->data,
  3068. _PyDateTime_DATE_DATASIZE);
  3069. return Py_BuildValue("(N)", field);
  3070. }
  3071. static PyObject *
  3072. date_reduce(PyDateTime_Date *self, PyObject *arg)
  3073. {
  3074. return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
  3075. }
  3076. static PyMethodDef date_methods[] = {
  3077. /* Class methods: */
  3078. DATETIME_DATE_FROMTIMESTAMP_METHODDEF
  3079. {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
  3080. METH_CLASS,
  3081. PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
  3082. "ordinal.")},
  3083. {"fromisoformat", (PyCFunction)date_fromisoformat, METH_O |
  3084. METH_CLASS,
  3085. PyDoc_STR("str -> Construct a date from a string in ISO 8601 format.")},
  3086. {"fromisocalendar", _PyCFunction_CAST(date_fromisocalendar),
  3087. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  3088. PyDoc_STR("int, int, int -> Construct a date from the ISO year, week "
  3089. "number and weekday.\n\n"
  3090. "This is the inverse of the date.isocalendar() function")},
  3091. {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
  3092. PyDoc_STR("Current date or datetime: same as "
  3093. "self.__class__.fromtimestamp(time.time()).")},
  3094. /* Instance methods: */
  3095. {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
  3096. PyDoc_STR("Return ctime() style string.")},
  3097. {"strftime", _PyCFunction_CAST(date_strftime), METH_VARARGS | METH_KEYWORDS,
  3098. PyDoc_STR("format -> strftime() style string.")},
  3099. {"__format__", (PyCFunction)date_format, METH_VARARGS,
  3100. PyDoc_STR("Formats self with strftime.")},
  3101. {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
  3102. PyDoc_STR("Return time tuple, compatible with time.localtime().")},
  3103. {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
  3104. PyDoc_STR("Return a named tuple containing ISO year, week number, and "
  3105. "weekday.")},
  3106. {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
  3107. PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
  3108. {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
  3109. PyDoc_STR("Return the day of the week represented by the date.\n"
  3110. "Monday == 1 ... Sunday == 7")},
  3111. {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
  3112. PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
  3113. "1 is day 1.")},
  3114. {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
  3115. PyDoc_STR("Return the day of the week represented by the date.\n"
  3116. "Monday == 0 ... Sunday == 6")},
  3117. {"replace", _PyCFunction_CAST(date_replace), METH_VARARGS | METH_KEYWORDS,
  3118. PyDoc_STR("Return date with new specified fields.")},
  3119. {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
  3120. PyDoc_STR("__reduce__() -> (cls, state)")},
  3121. {NULL, NULL}
  3122. };
  3123. static const char date_doc[] =
  3124. PyDoc_STR("date(year, month, day) --> date object");
  3125. static PyNumberMethods date_as_number = {
  3126. date_add, /* nb_add */
  3127. date_subtract, /* nb_subtract */
  3128. 0, /* nb_multiply */
  3129. 0, /* nb_remainder */
  3130. 0, /* nb_divmod */
  3131. 0, /* nb_power */
  3132. 0, /* nb_negative */
  3133. 0, /* nb_positive */
  3134. 0, /* nb_absolute */
  3135. 0, /* nb_bool */
  3136. };
  3137. static PyTypeObject PyDateTime_DateType = {
  3138. PyVarObject_HEAD_INIT(NULL, 0)
  3139. "datetime.date", /* tp_name */
  3140. sizeof(PyDateTime_Date), /* tp_basicsize */
  3141. 0, /* tp_itemsize */
  3142. 0, /* tp_dealloc */
  3143. 0, /* tp_vectorcall_offset */
  3144. 0, /* tp_getattr */
  3145. 0, /* tp_setattr */
  3146. 0, /* tp_as_async */
  3147. (reprfunc)date_repr, /* tp_repr */
  3148. &date_as_number, /* tp_as_number */
  3149. 0, /* tp_as_sequence */
  3150. 0, /* tp_as_mapping */
  3151. (hashfunc)date_hash, /* tp_hash */
  3152. 0, /* tp_call */
  3153. (reprfunc)date_str, /* tp_str */
  3154. PyObject_GenericGetAttr, /* tp_getattro */
  3155. 0, /* tp_setattro */
  3156. 0, /* tp_as_buffer */
  3157. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3158. date_doc, /* tp_doc */
  3159. 0, /* tp_traverse */
  3160. 0, /* tp_clear */
  3161. date_richcompare, /* tp_richcompare */
  3162. 0, /* tp_weaklistoffset */
  3163. 0, /* tp_iter */
  3164. 0, /* tp_iternext */
  3165. date_methods, /* tp_methods */
  3166. 0, /* tp_members */
  3167. date_getset, /* tp_getset */
  3168. 0, /* tp_base */
  3169. 0, /* tp_dict */
  3170. 0, /* tp_descr_get */
  3171. 0, /* tp_descr_set */
  3172. 0, /* tp_dictoffset */
  3173. 0, /* tp_init */
  3174. 0, /* tp_alloc */
  3175. date_new, /* tp_new */
  3176. 0, /* tp_free */
  3177. };
  3178. /*
  3179. * PyDateTime_TZInfo implementation.
  3180. */
  3181. /* This is a pure abstract base class, so doesn't do anything beyond
  3182. * raising NotImplemented exceptions. Real tzinfo classes need
  3183. * to derive from this. This is mostly for clarity, and for efficiency in
  3184. * datetime and time constructors (their tzinfo arguments need to
  3185. * be subclasses of this tzinfo class, which is easy and quick to check).
  3186. *
  3187. * Note: For reasons having to do with pickling of subclasses, we have
  3188. * to allow tzinfo objects to be instantiated. This wasn't an issue
  3189. * in the Python implementation (__init__() could raise NotImplementedError
  3190. * there without ill effect), but doing so in the C implementation hit a
  3191. * brick wall.
  3192. */
  3193. static PyObject *
  3194. tzinfo_nogo(const char* methodname)
  3195. {
  3196. PyErr_Format(PyExc_NotImplementedError,
  3197. "a tzinfo subclass must implement %s()",
  3198. methodname);
  3199. return NULL;
  3200. }
  3201. /* Methods. A subclass must implement these. */
  3202. static PyObject *
  3203. tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
  3204. {
  3205. return tzinfo_nogo("tzname");
  3206. }
  3207. static PyObject *
  3208. tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
  3209. {
  3210. return tzinfo_nogo("utcoffset");
  3211. }
  3212. static PyObject *
  3213. tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
  3214. {
  3215. return tzinfo_nogo("dst");
  3216. }
  3217. static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
  3218. PyDateTime_Delta *delta,
  3219. int factor);
  3220. static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
  3221. static PyObject *datetime_dst(PyObject *self, PyObject *);
  3222. static PyObject *
  3223. tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
  3224. {
  3225. PyObject *result = NULL;
  3226. PyObject *off = NULL, *dst = NULL;
  3227. PyDateTime_Delta *delta = NULL;
  3228. if (!PyDateTime_Check(dt)) {
  3229. PyErr_SetString(PyExc_TypeError,
  3230. "fromutc: argument must be a datetime");
  3231. return NULL;
  3232. }
  3233. if (GET_DT_TZINFO(dt) != (PyObject *)self) {
  3234. PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
  3235. "is not self");
  3236. return NULL;
  3237. }
  3238. off = datetime_utcoffset(dt, NULL);
  3239. if (off == NULL)
  3240. return NULL;
  3241. if (off == Py_None) {
  3242. PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
  3243. "utcoffset() result required");
  3244. goto Fail;
  3245. }
  3246. dst = datetime_dst(dt, NULL);
  3247. if (dst == NULL)
  3248. goto Fail;
  3249. if (dst == Py_None) {
  3250. PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
  3251. "dst() result required");
  3252. goto Fail;
  3253. }
  3254. delta = (PyDateTime_Delta *)delta_subtract(off, dst);
  3255. if (delta == NULL)
  3256. goto Fail;
  3257. result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
  3258. if (result == NULL)
  3259. goto Fail;
  3260. Py_DECREF(dst);
  3261. dst = call_dst(GET_DT_TZINFO(dt), result);
  3262. if (dst == NULL)
  3263. goto Fail;
  3264. if (dst == Py_None)
  3265. goto Inconsistent;
  3266. if (delta_bool((PyDateTime_Delta *)dst) != 0) {
  3267. Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
  3268. (PyDateTime_Delta *)dst, 1));
  3269. if (result == NULL)
  3270. goto Fail;
  3271. }
  3272. Py_DECREF(delta);
  3273. Py_DECREF(dst);
  3274. Py_DECREF(off);
  3275. return result;
  3276. Inconsistent:
  3277. PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave "
  3278. "inconsistent results; cannot convert");
  3279. /* fall through to failure */
  3280. Fail:
  3281. Py_XDECREF(off);
  3282. Py_XDECREF(dst);
  3283. Py_XDECREF(delta);
  3284. Py_XDECREF(result);
  3285. return NULL;
  3286. }
  3287. /*
  3288. * Pickle support. This is solely so that tzinfo subclasses can use
  3289. * pickling -- tzinfo itself is supposed to be uninstantiable.
  3290. */
  3291. static PyObject *
  3292. tzinfo_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
  3293. {
  3294. PyObject *args, *state;
  3295. PyObject *getinitargs;
  3296. if (_PyObject_LookupAttr(self, &_Py_ID(__getinitargs__), &getinitargs) < 0) {
  3297. return NULL;
  3298. }
  3299. if (getinitargs != NULL) {
  3300. args = PyObject_CallNoArgs(getinitargs);
  3301. Py_DECREF(getinitargs);
  3302. }
  3303. else {
  3304. args = PyTuple_New(0);
  3305. }
  3306. if (args == NULL) {
  3307. return NULL;
  3308. }
  3309. state = _PyObject_GetState(self);
  3310. if (state == NULL) {
  3311. Py_DECREF(args);
  3312. return NULL;
  3313. }
  3314. return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
  3315. }
  3316. static PyMethodDef tzinfo_methods[] = {
  3317. {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
  3318. PyDoc_STR("datetime -> string name of time zone.")},
  3319. {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
  3320. PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
  3321. "values indicating West of UTC")},
  3322. {"dst", (PyCFunction)tzinfo_dst, METH_O,
  3323. PyDoc_STR("datetime -> DST offset as timedelta positive east of UTC.")},
  3324. {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
  3325. PyDoc_STR("datetime in UTC -> datetime in local time.")},
  3326. {"__reduce__", tzinfo_reduce, METH_NOARGS,
  3327. PyDoc_STR("-> (cls, state)")},
  3328. {NULL, NULL}
  3329. };
  3330. static const char tzinfo_doc[] =
  3331. PyDoc_STR("Abstract base class for time zone info objects.");
  3332. static PyTypeObject PyDateTime_TZInfoType = {
  3333. PyVarObject_HEAD_INIT(NULL, 0)
  3334. "datetime.tzinfo", /* tp_name */
  3335. sizeof(PyDateTime_TZInfo), /* tp_basicsize */
  3336. 0, /* tp_itemsize */
  3337. 0, /* tp_dealloc */
  3338. 0, /* tp_vectorcall_offset */
  3339. 0, /* tp_getattr */
  3340. 0, /* tp_setattr */
  3341. 0, /* tp_as_async */
  3342. 0, /* tp_repr */
  3343. 0, /* tp_as_number */
  3344. 0, /* tp_as_sequence */
  3345. 0, /* tp_as_mapping */
  3346. 0, /* tp_hash */
  3347. 0, /* tp_call */
  3348. 0, /* tp_str */
  3349. PyObject_GenericGetAttr, /* tp_getattro */
  3350. 0, /* tp_setattro */
  3351. 0, /* tp_as_buffer */
  3352. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3353. tzinfo_doc, /* tp_doc */
  3354. 0, /* tp_traverse */
  3355. 0, /* tp_clear */
  3356. 0, /* tp_richcompare */
  3357. 0, /* tp_weaklistoffset */
  3358. 0, /* tp_iter */
  3359. 0, /* tp_iternext */
  3360. tzinfo_methods, /* tp_methods */
  3361. 0, /* tp_members */
  3362. 0, /* tp_getset */
  3363. 0, /* tp_base */
  3364. 0, /* tp_dict */
  3365. 0, /* tp_descr_get */
  3366. 0, /* tp_descr_set */
  3367. 0, /* tp_dictoffset */
  3368. 0, /* tp_init */
  3369. 0, /* tp_alloc */
  3370. PyType_GenericNew, /* tp_new */
  3371. 0, /* tp_free */
  3372. };
  3373. static char *timezone_kws[] = {"offset", "name", NULL};
  3374. static PyObject *
  3375. timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  3376. {
  3377. PyObject *offset;
  3378. PyObject *name = NULL;
  3379. if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
  3380. &PyDateTime_DeltaType, &offset, &name))
  3381. return new_timezone(offset, name);
  3382. return NULL;
  3383. }
  3384. static void
  3385. timezone_dealloc(PyDateTime_TimeZone *self)
  3386. {
  3387. Py_CLEAR(self->offset);
  3388. Py_CLEAR(self->name);
  3389. Py_TYPE(self)->tp_free((PyObject *)self);
  3390. }
  3391. static PyObject *
  3392. timezone_richcompare(PyDateTime_TimeZone *self,
  3393. PyDateTime_TimeZone *other, int op)
  3394. {
  3395. if (op != Py_EQ && op != Py_NE)
  3396. Py_RETURN_NOTIMPLEMENTED;
  3397. if (!PyTimezone_Check(other)) {
  3398. Py_RETURN_NOTIMPLEMENTED;
  3399. }
  3400. return delta_richcompare(self->offset, other->offset, op);
  3401. }
  3402. static Py_hash_t
  3403. timezone_hash(PyDateTime_TimeZone *self)
  3404. {
  3405. return delta_hash((PyDateTime_Delta *)self->offset);
  3406. }
  3407. /* Check argument type passed to tzname, utcoffset, or dst methods.
  3408. Returns 0 for good argument. Returns -1 and sets exception info
  3409. otherwise.
  3410. */
  3411. static int
  3412. _timezone_check_argument(PyObject *dt, const char *meth)
  3413. {
  3414. if (dt == Py_None || PyDateTime_Check(dt))
  3415. return 0;
  3416. PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
  3417. " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
  3418. return -1;
  3419. }
  3420. static PyObject *
  3421. timezone_repr(PyDateTime_TimeZone *self)
  3422. {
  3423. /* Note that although timezone is not subclassable, it is convenient
  3424. to use Py_TYPE(self)->tp_name here. */
  3425. const char *type_name = Py_TYPE(self)->tp_name;
  3426. if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
  3427. return PyUnicode_FromFormat("%s.utc", type_name);
  3428. if (self->name == NULL)
  3429. return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
  3430. return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
  3431. self->name);
  3432. }
  3433. static PyObject *
  3434. timezone_str(PyDateTime_TimeZone *self)
  3435. {
  3436. int hours, minutes, seconds, microseconds;
  3437. PyObject *offset;
  3438. char sign;
  3439. if (self->name != NULL) {
  3440. return Py_NewRef(self->name);
  3441. }
  3442. if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
  3443. (GET_TD_DAYS(self->offset) == 0 &&
  3444. GET_TD_SECONDS(self->offset) == 0 &&
  3445. GET_TD_MICROSECONDS(self->offset) == 0))
  3446. return PyUnicode_FromString("UTC");
  3447. /* Offset is normalized, so it is negative if days < 0 */
  3448. if (GET_TD_DAYS(self->offset) < 0) {
  3449. sign = '-';
  3450. offset = delta_negative((PyDateTime_Delta *)self->offset);
  3451. if (offset == NULL)
  3452. return NULL;
  3453. }
  3454. else {
  3455. sign = '+';
  3456. offset = Py_NewRef(self->offset);
  3457. }
  3458. /* Offset is not negative here. */
  3459. microseconds = GET_TD_MICROSECONDS(offset);
  3460. seconds = GET_TD_SECONDS(offset);
  3461. Py_DECREF(offset);
  3462. minutes = divmod(seconds, 60, &seconds);
  3463. hours = divmod(minutes, 60, &minutes);
  3464. if (microseconds != 0) {
  3465. return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d.%06d",
  3466. sign, hours, minutes,
  3467. seconds, microseconds);
  3468. }
  3469. if (seconds != 0) {
  3470. return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d",
  3471. sign, hours, minutes, seconds);
  3472. }
  3473. return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
  3474. }
  3475. static PyObject *
  3476. timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
  3477. {
  3478. if (_timezone_check_argument(dt, "tzname") == -1)
  3479. return NULL;
  3480. return timezone_str(self);
  3481. }
  3482. static PyObject *
  3483. timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
  3484. {
  3485. if (_timezone_check_argument(dt, "utcoffset") == -1)
  3486. return NULL;
  3487. return Py_NewRef(self->offset);
  3488. }
  3489. static PyObject *
  3490. timezone_dst(PyObject *self, PyObject *dt)
  3491. {
  3492. if (_timezone_check_argument(dt, "dst") == -1)
  3493. return NULL;
  3494. Py_RETURN_NONE;
  3495. }
  3496. static PyObject *
  3497. timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
  3498. {
  3499. if (!PyDateTime_Check(dt)) {
  3500. PyErr_SetString(PyExc_TypeError,
  3501. "fromutc: argument must be a datetime");
  3502. return NULL;
  3503. }
  3504. if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
  3505. PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
  3506. "is not self");
  3507. return NULL;
  3508. }
  3509. return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
  3510. }
  3511. static PyObject *
  3512. timezone_getinitargs(PyDateTime_TimeZone *self, PyObject *Py_UNUSED(ignored))
  3513. {
  3514. if (self->name == NULL)
  3515. return Py_BuildValue("(O)", self->offset);
  3516. return Py_BuildValue("(OO)", self->offset, self->name);
  3517. }
  3518. static PyMethodDef timezone_methods[] = {
  3519. {"tzname", (PyCFunction)timezone_tzname, METH_O,
  3520. PyDoc_STR("If name is specified when timezone is created, returns the name."
  3521. " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
  3522. {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
  3523. PyDoc_STR("Return fixed offset.")},
  3524. {"dst", (PyCFunction)timezone_dst, METH_O,
  3525. PyDoc_STR("Return None.")},
  3526. {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
  3527. PyDoc_STR("datetime in UTC -> datetime in local time.")},
  3528. {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
  3529. PyDoc_STR("pickle support")},
  3530. {NULL, NULL}
  3531. };
  3532. static const char timezone_doc[] =
  3533. PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
  3534. static PyTypeObject PyDateTime_TimeZoneType = {
  3535. PyVarObject_HEAD_INIT(NULL, 0)
  3536. "datetime.timezone", /* tp_name */
  3537. sizeof(PyDateTime_TimeZone), /* tp_basicsize */
  3538. 0, /* tp_itemsize */
  3539. (destructor)timezone_dealloc, /* tp_dealloc */
  3540. 0, /* tp_vectorcall_offset */
  3541. 0, /* tp_getattr */
  3542. 0, /* tp_setattr */
  3543. 0, /* tp_as_async */
  3544. (reprfunc)timezone_repr, /* tp_repr */
  3545. 0, /* tp_as_number */
  3546. 0, /* tp_as_sequence */
  3547. 0, /* tp_as_mapping */
  3548. (hashfunc)timezone_hash, /* tp_hash */
  3549. 0, /* tp_call */
  3550. (reprfunc)timezone_str, /* tp_str */
  3551. 0, /* tp_getattro */
  3552. 0, /* tp_setattro */
  3553. 0, /* tp_as_buffer */
  3554. Py_TPFLAGS_DEFAULT, /* tp_flags */
  3555. timezone_doc, /* tp_doc */
  3556. 0, /* tp_traverse */
  3557. 0, /* tp_clear */
  3558. (richcmpfunc)timezone_richcompare,/* tp_richcompare */
  3559. 0, /* tp_weaklistoffset */
  3560. 0, /* tp_iter */
  3561. 0, /* tp_iternext */
  3562. timezone_methods, /* tp_methods */
  3563. 0, /* tp_members */
  3564. 0, /* tp_getset */
  3565. 0, /* tp_base; filled in PyInit__datetime */
  3566. 0, /* tp_dict */
  3567. 0, /* tp_descr_get */
  3568. 0, /* tp_descr_set */
  3569. 0, /* tp_dictoffset */
  3570. 0, /* tp_init */
  3571. 0, /* tp_alloc */
  3572. timezone_new, /* tp_new */
  3573. };
  3574. /*
  3575. * PyDateTime_Time implementation.
  3576. */
  3577. /* Accessor properties.
  3578. */
  3579. static PyObject *
  3580. time_hour(PyDateTime_Time *self, void *unused)
  3581. {
  3582. return PyLong_FromLong(TIME_GET_HOUR(self));
  3583. }
  3584. static PyObject *
  3585. time_minute(PyDateTime_Time *self, void *unused)
  3586. {
  3587. return PyLong_FromLong(TIME_GET_MINUTE(self));
  3588. }
  3589. /* The name time_second conflicted with some platform header file. */
  3590. static PyObject *
  3591. py_time_second(PyDateTime_Time *self, void *unused)
  3592. {
  3593. return PyLong_FromLong(TIME_GET_SECOND(self));
  3594. }
  3595. static PyObject *
  3596. time_microsecond(PyDateTime_Time *self, void *unused)
  3597. {
  3598. return PyLong_FromLong(TIME_GET_MICROSECOND(self));
  3599. }
  3600. static PyObject *
  3601. time_tzinfo(PyDateTime_Time *self, void *unused)
  3602. {
  3603. PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
  3604. return Py_NewRef(result);
  3605. }
  3606. static PyObject *
  3607. time_fold(PyDateTime_Time *self, void *unused)
  3608. {
  3609. return PyLong_FromLong(TIME_GET_FOLD(self));
  3610. }
  3611. static PyGetSetDef time_getset[] = {
  3612. {"hour", (getter)time_hour},
  3613. {"minute", (getter)time_minute},
  3614. {"second", (getter)py_time_second},
  3615. {"microsecond", (getter)time_microsecond},
  3616. {"tzinfo", (getter)time_tzinfo},
  3617. {"fold", (getter)time_fold},
  3618. {NULL}
  3619. };
  3620. /*
  3621. * Constructors.
  3622. */
  3623. static char *time_kws[] = {"hour", "minute", "second", "microsecond",
  3624. "tzinfo", "fold", NULL};
  3625. static PyObject *
  3626. time_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
  3627. {
  3628. PyDateTime_Time *me;
  3629. char aware = (char)(tzinfo != Py_None);
  3630. if (aware && check_tzinfo_subclass(tzinfo) < 0) {
  3631. PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
  3632. return NULL;
  3633. }
  3634. me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
  3635. if (me != NULL) {
  3636. const char *pdata = PyBytes_AS_STRING(state);
  3637. memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
  3638. me->hashcode = -1;
  3639. me->hastzinfo = aware;
  3640. if (aware) {
  3641. me->tzinfo = Py_NewRef(tzinfo);
  3642. }
  3643. if (pdata[0] & (1 << 7)) {
  3644. me->data[0] -= 128;
  3645. me->fold = 1;
  3646. }
  3647. else {
  3648. me->fold = 0;
  3649. }
  3650. }
  3651. return (PyObject *)me;
  3652. }
  3653. static PyObject *
  3654. time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  3655. {
  3656. PyObject *self = NULL;
  3657. int hour = 0;
  3658. int minute = 0;
  3659. int second = 0;
  3660. int usecond = 0;
  3661. PyObject *tzinfo = Py_None;
  3662. int fold = 0;
  3663. /* Check for invocation from pickle with __getstate__ state */
  3664. if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
  3665. PyObject *state = PyTuple_GET_ITEM(args, 0);
  3666. if (PyTuple_GET_SIZE(args) == 2) {
  3667. tzinfo = PyTuple_GET_ITEM(args, 1);
  3668. }
  3669. if (PyBytes_Check(state)) {
  3670. if (PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
  3671. (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
  3672. {
  3673. return time_from_pickle(type, state, tzinfo);
  3674. }
  3675. }
  3676. else if (PyUnicode_Check(state)) {
  3677. if (PyUnicode_READY(state)) {
  3678. return NULL;
  3679. }
  3680. if (PyUnicode_GET_LENGTH(state) == _PyDateTime_TIME_DATASIZE &&
  3681. (0x7F & PyUnicode_READ_CHAR(state, 0)) < 24)
  3682. {
  3683. state = PyUnicode_AsLatin1String(state);
  3684. if (state == NULL) {
  3685. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
  3686. /* More informative error message. */
  3687. PyErr_SetString(PyExc_ValueError,
  3688. "Failed to encode latin1 string when unpickling "
  3689. "a time object. "
  3690. "pickle.load(data, encoding='latin1') is assumed.");
  3691. }
  3692. return NULL;
  3693. }
  3694. self = time_from_pickle(type, state, tzinfo);
  3695. Py_DECREF(state);
  3696. return self;
  3697. }
  3698. }
  3699. tzinfo = Py_None;
  3700. }
  3701. if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
  3702. &hour, &minute, &second, &usecond,
  3703. &tzinfo, &fold)) {
  3704. self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
  3705. type);
  3706. }
  3707. return self;
  3708. }
  3709. /*
  3710. * Destructor.
  3711. */
  3712. static void
  3713. time_dealloc(PyDateTime_Time *self)
  3714. {
  3715. if (HASTZINFO(self)) {
  3716. Py_XDECREF(self->tzinfo);
  3717. }
  3718. Py_TYPE(self)->tp_free((PyObject *)self);
  3719. }
  3720. /*
  3721. * Indirect access to tzinfo methods.
  3722. */
  3723. /* These are all METH_NOARGS, so don't need to check the arglist. */
  3724. static PyObject *
  3725. time_utcoffset(PyObject *self, PyObject *unused) {
  3726. return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
  3727. }
  3728. static PyObject *
  3729. time_dst(PyObject *self, PyObject *unused) {
  3730. return call_dst(GET_TIME_TZINFO(self), Py_None);
  3731. }
  3732. static PyObject *
  3733. time_tzname(PyDateTime_Time *self, PyObject *unused) {
  3734. return call_tzname(GET_TIME_TZINFO(self), Py_None);
  3735. }
  3736. /*
  3737. * Various ways to turn a time into a string.
  3738. */
  3739. static PyObject *
  3740. time_repr(PyDateTime_Time *self)
  3741. {
  3742. const char *type_name = Py_TYPE(self)->tp_name;
  3743. int h = TIME_GET_HOUR(self);
  3744. int m = TIME_GET_MINUTE(self);
  3745. int s = TIME_GET_SECOND(self);
  3746. int us = TIME_GET_MICROSECOND(self);
  3747. int fold = TIME_GET_FOLD(self);
  3748. PyObject *result = NULL;
  3749. if (us)
  3750. result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
  3751. type_name, h, m, s, us);
  3752. else if (s)
  3753. result = PyUnicode_FromFormat("%s(%d, %d, %d)",
  3754. type_name, h, m, s);
  3755. else
  3756. result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
  3757. if (result != NULL && HASTZINFO(self))
  3758. result = append_keyword_tzinfo(result, self->tzinfo);
  3759. if (result != NULL && fold)
  3760. result = append_keyword_fold(result, fold);
  3761. return result;
  3762. }
  3763. static PyObject *
  3764. time_str(PyDateTime_Time *self)
  3765. {
  3766. return PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(isoformat));
  3767. }
  3768. static PyObject *
  3769. time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
  3770. {
  3771. char buf[100];
  3772. const char *timespec = NULL;
  3773. static char *keywords[] = {"timespec", NULL};
  3774. PyObject *result;
  3775. int us = TIME_GET_MICROSECOND(self);
  3776. static const char *specs[][2] = {
  3777. {"hours", "%02d"},
  3778. {"minutes", "%02d:%02d"},
  3779. {"seconds", "%02d:%02d:%02d"},
  3780. {"milliseconds", "%02d:%02d:%02d.%03d"},
  3781. {"microseconds", "%02d:%02d:%02d.%06d"},
  3782. };
  3783. size_t given_spec;
  3784. if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
  3785. return NULL;
  3786. if (timespec == NULL || strcmp(timespec, "auto") == 0) {
  3787. if (us == 0) {
  3788. /* seconds */
  3789. given_spec = 2;
  3790. }
  3791. else {
  3792. /* microseconds */
  3793. given_spec = 4;
  3794. }
  3795. }
  3796. else {
  3797. for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
  3798. if (strcmp(timespec, specs[given_spec][0]) == 0) {
  3799. if (given_spec == 3) {
  3800. /* milliseconds */
  3801. us = us / 1000;
  3802. }
  3803. break;
  3804. }
  3805. }
  3806. }
  3807. if (given_spec == Py_ARRAY_LENGTH(specs)) {
  3808. PyErr_Format(PyExc_ValueError, "Unknown timespec value");
  3809. return NULL;
  3810. }
  3811. else {
  3812. result = PyUnicode_FromFormat(specs[given_spec][1],
  3813. TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
  3814. TIME_GET_SECOND(self), us);
  3815. }
  3816. if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
  3817. return result;
  3818. /* We need to append the UTC offset. */
  3819. if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
  3820. Py_None) < 0) {
  3821. Py_DECREF(result);
  3822. return NULL;
  3823. }
  3824. PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
  3825. return result;
  3826. }
  3827. static PyObject *
  3828. time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
  3829. {
  3830. PyObject *result;
  3831. PyObject *tuple;
  3832. PyObject *format;
  3833. static char *keywords[] = {"format", NULL};
  3834. if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
  3835. &format))
  3836. return NULL;
  3837. /* Python's strftime does insane things with the year part of the
  3838. * timetuple. The year is forced to (the otherwise nonsensical)
  3839. * 1900 to work around that.
  3840. */
  3841. tuple = Py_BuildValue("iiiiiiiii",
  3842. 1900, 1, 1, /* year, month, day */
  3843. TIME_GET_HOUR(self),
  3844. TIME_GET_MINUTE(self),
  3845. TIME_GET_SECOND(self),
  3846. 0, 1, -1); /* weekday, daynum, dst */
  3847. if (tuple == NULL)
  3848. return NULL;
  3849. assert(PyTuple_Size(tuple) == 9);
  3850. result = wrap_strftime((PyObject *)self, format, tuple,
  3851. Py_None);
  3852. Py_DECREF(tuple);
  3853. return result;
  3854. }
  3855. /*
  3856. * Miscellaneous methods.
  3857. */
  3858. static PyObject *
  3859. time_richcompare(PyObject *self, PyObject *other, int op)
  3860. {
  3861. PyObject *result = NULL;
  3862. PyObject *offset1, *offset2;
  3863. int diff;
  3864. if (! PyTime_Check(other))
  3865. Py_RETURN_NOTIMPLEMENTED;
  3866. if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
  3867. diff = memcmp(((PyDateTime_Time *)self)->data,
  3868. ((PyDateTime_Time *)other)->data,
  3869. _PyDateTime_TIME_DATASIZE);
  3870. return diff_to_bool(diff, op);
  3871. }
  3872. offset1 = time_utcoffset(self, NULL);
  3873. if (offset1 == NULL)
  3874. return NULL;
  3875. offset2 = time_utcoffset(other, NULL);
  3876. if (offset2 == NULL)
  3877. goto done;
  3878. /* If they're both naive, or both aware and have the same offsets,
  3879. * we get off cheap. Note that if they're both naive, offset1 ==
  3880. * offset2 == Py_None at this point.
  3881. */
  3882. if ((offset1 == offset2) ||
  3883. (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
  3884. delta_cmp(offset1, offset2) == 0)) {
  3885. diff = memcmp(((PyDateTime_Time *)self)->data,
  3886. ((PyDateTime_Time *)other)->data,
  3887. _PyDateTime_TIME_DATASIZE);
  3888. result = diff_to_bool(diff, op);
  3889. }
  3890. /* The hard case: both aware with different UTC offsets */
  3891. else if (offset1 != Py_None && offset2 != Py_None) {
  3892. int offsecs1, offsecs2;
  3893. assert(offset1 != offset2); /* else last "if" handled it */
  3894. offsecs1 = TIME_GET_HOUR(self) * 3600 +
  3895. TIME_GET_MINUTE(self) * 60 +
  3896. TIME_GET_SECOND(self) -
  3897. GET_TD_DAYS(offset1) * 86400 -
  3898. GET_TD_SECONDS(offset1);
  3899. offsecs2 = TIME_GET_HOUR(other) * 3600 +
  3900. TIME_GET_MINUTE(other) * 60 +
  3901. TIME_GET_SECOND(other) -
  3902. GET_TD_DAYS(offset2) * 86400 -
  3903. GET_TD_SECONDS(offset2);
  3904. diff = offsecs1 - offsecs2;
  3905. if (diff == 0)
  3906. diff = TIME_GET_MICROSECOND(self) -
  3907. TIME_GET_MICROSECOND(other);
  3908. result = diff_to_bool(diff, op);
  3909. }
  3910. else if (op == Py_EQ) {
  3911. result = Py_NewRef(Py_False);
  3912. }
  3913. else if (op == Py_NE) {
  3914. result = Py_NewRef(Py_True);
  3915. }
  3916. else {
  3917. PyErr_SetString(PyExc_TypeError,
  3918. "can't compare offset-naive and "
  3919. "offset-aware times");
  3920. }
  3921. done:
  3922. Py_DECREF(offset1);
  3923. Py_XDECREF(offset2);
  3924. return result;
  3925. }
  3926. static Py_hash_t
  3927. time_hash(PyDateTime_Time *self)
  3928. {
  3929. if (self->hashcode == -1) {
  3930. PyObject *offset, *self0;
  3931. if (TIME_GET_FOLD(self)) {
  3932. self0 = new_time_ex2(TIME_GET_HOUR(self),
  3933. TIME_GET_MINUTE(self),
  3934. TIME_GET_SECOND(self),
  3935. TIME_GET_MICROSECOND(self),
  3936. HASTZINFO(self) ? self->tzinfo : Py_None,
  3937. 0, Py_TYPE(self));
  3938. if (self0 == NULL)
  3939. return -1;
  3940. }
  3941. else {
  3942. self0 = Py_NewRef(self);
  3943. }
  3944. offset = time_utcoffset(self0, NULL);
  3945. Py_DECREF(self0);
  3946. if (offset == NULL)
  3947. return -1;
  3948. /* Reduce this to a hash of another object. */
  3949. if (offset == Py_None)
  3950. self->hashcode = generic_hash(
  3951. (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
  3952. else {
  3953. PyObject *temp1, *temp2;
  3954. int seconds, microseconds;
  3955. assert(HASTZINFO(self));
  3956. seconds = TIME_GET_HOUR(self) * 3600 +
  3957. TIME_GET_MINUTE(self) * 60 +
  3958. TIME_GET_SECOND(self);
  3959. microseconds = TIME_GET_MICROSECOND(self);
  3960. temp1 = new_delta(0, seconds, microseconds, 1);
  3961. if (temp1 == NULL) {
  3962. Py_DECREF(offset);
  3963. return -1;
  3964. }
  3965. temp2 = delta_subtract(temp1, offset);
  3966. Py_DECREF(temp1);
  3967. if (temp2 == NULL) {
  3968. Py_DECREF(offset);
  3969. return -1;
  3970. }
  3971. self->hashcode = PyObject_Hash(temp2);
  3972. Py_DECREF(temp2);
  3973. }
  3974. Py_DECREF(offset);
  3975. }
  3976. return self->hashcode;
  3977. }
  3978. static PyObject *
  3979. time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
  3980. {
  3981. PyObject *clone;
  3982. PyObject *tuple;
  3983. int hh = TIME_GET_HOUR(self);
  3984. int mm = TIME_GET_MINUTE(self);
  3985. int ss = TIME_GET_SECOND(self);
  3986. int us = TIME_GET_MICROSECOND(self);
  3987. PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
  3988. int fold = TIME_GET_FOLD(self);
  3989. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
  3990. time_kws,
  3991. &hh, &mm, &ss, &us, &tzinfo, &fold))
  3992. return NULL;
  3993. if (fold != 0 && fold != 1) {
  3994. PyErr_SetString(PyExc_ValueError,
  3995. "fold must be either 0 or 1");
  3996. return NULL;
  3997. }
  3998. tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
  3999. if (tuple == NULL)
  4000. return NULL;
  4001. clone = time_new(Py_TYPE(self), tuple, NULL);
  4002. if (clone != NULL) {
  4003. TIME_SET_FOLD(clone, fold);
  4004. }
  4005. Py_DECREF(tuple);
  4006. return clone;
  4007. }
  4008. static PyObject *
  4009. time_fromisoformat(PyObject *cls, PyObject *tstr) {
  4010. assert(tstr != NULL);
  4011. if (!PyUnicode_Check(tstr)) {
  4012. PyErr_SetString(PyExc_TypeError, "fromisoformat: argument must be str");
  4013. return NULL;
  4014. }
  4015. Py_ssize_t len;
  4016. const char *p = PyUnicode_AsUTF8AndSize(tstr, &len);
  4017. if (p == NULL) {
  4018. goto invalid_string_error;
  4019. }
  4020. // The spec actually requires that time-only ISO 8601 strings start with
  4021. // T, but the extended format allows this to be omitted as long as there
  4022. // is no ambiguity with date strings.
  4023. if (*p == 'T') {
  4024. ++p;
  4025. len -= 1;
  4026. }
  4027. int hour = 0, minute = 0, second = 0, microsecond = 0;
  4028. int tzoffset = 0, tzimicrosecond = 0;
  4029. int rv = parse_isoformat_time(p, len,
  4030. &hour, &minute, &second, &microsecond,
  4031. &tzoffset, &tzimicrosecond);
  4032. if (rv < 0) {
  4033. goto invalid_string_error;
  4034. }
  4035. PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset,
  4036. tzimicrosecond);
  4037. if (tzinfo == NULL) {
  4038. return NULL;
  4039. }
  4040. PyObject *t;
  4041. if ( (PyTypeObject *)cls == &PyDateTime_TimeType ) {
  4042. t = new_time(hour, minute, second, microsecond, tzinfo, 0);
  4043. } else {
  4044. t = PyObject_CallFunction(cls, "iiiiO",
  4045. hour, minute, second, microsecond, tzinfo);
  4046. }
  4047. Py_DECREF(tzinfo);
  4048. return t;
  4049. invalid_string_error:
  4050. PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", tstr);
  4051. return NULL;
  4052. }
  4053. /* Pickle support, a simple use of __reduce__. */
  4054. /* Let basestate be the non-tzinfo data string.
  4055. * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
  4056. * So it's a tuple in any (non-error) case.
  4057. * __getstate__ isn't exposed.
  4058. */
  4059. static PyObject *
  4060. time_getstate(PyDateTime_Time *self, int proto)
  4061. {
  4062. PyObject *basestate;
  4063. PyObject *result = NULL;
  4064. basestate = PyBytes_FromStringAndSize((char *)self->data,
  4065. _PyDateTime_TIME_DATASIZE);
  4066. if (basestate != NULL) {
  4067. if (proto > 3 && TIME_GET_FOLD(self))
  4068. /* Set the first bit of the first byte */
  4069. PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
  4070. if (! HASTZINFO(self) || self->tzinfo == Py_None)
  4071. result = PyTuple_Pack(1, basestate);
  4072. else
  4073. result = PyTuple_Pack(2, basestate, self->tzinfo);
  4074. Py_DECREF(basestate);
  4075. }
  4076. return result;
  4077. }
  4078. static PyObject *
  4079. time_reduce_ex(PyDateTime_Time *self, PyObject *args)
  4080. {
  4081. int proto;
  4082. if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
  4083. return NULL;
  4084. return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
  4085. }
  4086. static PyObject *
  4087. time_reduce(PyDateTime_Time *self, PyObject *arg)
  4088. {
  4089. return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
  4090. }
  4091. static PyMethodDef time_methods[] = {
  4092. {"isoformat", _PyCFunction_CAST(time_isoformat), METH_VARARGS | METH_KEYWORDS,
  4093. PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
  4094. "[+HH:MM].\n\n"
  4095. "The optional argument timespec specifies the number "
  4096. "of additional terms\nof the time to include. Valid "
  4097. "options are 'auto', 'hours', 'minutes',\n'seconds', "
  4098. "'milliseconds' and 'microseconds'.\n")},
  4099. {"strftime", _PyCFunction_CAST(time_strftime), METH_VARARGS | METH_KEYWORDS,
  4100. PyDoc_STR("format -> strftime() style string.")},
  4101. {"__format__", (PyCFunction)date_format, METH_VARARGS,
  4102. PyDoc_STR("Formats self with strftime.")},
  4103. {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
  4104. PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
  4105. {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
  4106. PyDoc_STR("Return self.tzinfo.tzname(self).")},
  4107. {"dst", (PyCFunction)time_dst, METH_NOARGS,
  4108. PyDoc_STR("Return self.tzinfo.dst(self).")},
  4109. {"replace", _PyCFunction_CAST(time_replace), METH_VARARGS | METH_KEYWORDS,
  4110. PyDoc_STR("Return time with new specified fields.")},
  4111. {"fromisoformat", (PyCFunction)time_fromisoformat, METH_O | METH_CLASS,
  4112. PyDoc_STR("string -> time from a string in ISO 8601 format")},
  4113. {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
  4114. PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
  4115. {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
  4116. PyDoc_STR("__reduce__() -> (cls, state)")},
  4117. {NULL, NULL}
  4118. };
  4119. static const char time_doc[] =
  4120. PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
  4121. \n\
  4122. All arguments are optional. tzinfo may be None, or an instance of\n\
  4123. a tzinfo subclass. The remaining arguments may be ints.\n");
  4124. static PyTypeObject PyDateTime_TimeType = {
  4125. PyVarObject_HEAD_INIT(NULL, 0)
  4126. "datetime.time", /* tp_name */
  4127. sizeof(PyDateTime_Time), /* tp_basicsize */
  4128. 0, /* tp_itemsize */
  4129. (destructor)time_dealloc, /* tp_dealloc */
  4130. 0, /* tp_vectorcall_offset */
  4131. 0, /* tp_getattr */
  4132. 0, /* tp_setattr */
  4133. 0, /* tp_as_async */
  4134. (reprfunc)time_repr, /* tp_repr */
  4135. 0, /* tp_as_number */
  4136. 0, /* tp_as_sequence */
  4137. 0, /* tp_as_mapping */
  4138. (hashfunc)time_hash, /* tp_hash */
  4139. 0, /* tp_call */
  4140. (reprfunc)time_str, /* tp_str */
  4141. PyObject_GenericGetAttr, /* tp_getattro */
  4142. 0, /* tp_setattro */
  4143. 0, /* tp_as_buffer */
  4144. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  4145. time_doc, /* tp_doc */
  4146. 0, /* tp_traverse */
  4147. 0, /* tp_clear */
  4148. time_richcompare, /* tp_richcompare */
  4149. 0, /* tp_weaklistoffset */
  4150. 0, /* tp_iter */
  4151. 0, /* tp_iternext */
  4152. time_methods, /* tp_methods */
  4153. 0, /* tp_members */
  4154. time_getset, /* tp_getset */
  4155. 0, /* tp_base */
  4156. 0, /* tp_dict */
  4157. 0, /* tp_descr_get */
  4158. 0, /* tp_descr_set */
  4159. 0, /* tp_dictoffset */
  4160. 0, /* tp_init */
  4161. time_alloc, /* tp_alloc */
  4162. time_new, /* tp_new */
  4163. 0, /* tp_free */
  4164. };
  4165. /*
  4166. * PyDateTime_DateTime implementation.
  4167. */
  4168. /* Accessor properties. Properties for day, month, and year are inherited
  4169. * from date.
  4170. */
  4171. static PyObject *
  4172. datetime_hour(PyDateTime_DateTime *self, void *unused)
  4173. {
  4174. return PyLong_FromLong(DATE_GET_HOUR(self));
  4175. }
  4176. static PyObject *
  4177. datetime_minute(PyDateTime_DateTime *self, void *unused)
  4178. {
  4179. return PyLong_FromLong(DATE_GET_MINUTE(self));
  4180. }
  4181. static PyObject *
  4182. datetime_second(PyDateTime_DateTime *self, void *unused)
  4183. {
  4184. return PyLong_FromLong(DATE_GET_SECOND(self));
  4185. }
  4186. static PyObject *
  4187. datetime_microsecond(PyDateTime_DateTime *self, void *unused)
  4188. {
  4189. return PyLong_FromLong(DATE_GET_MICROSECOND(self));
  4190. }
  4191. static PyObject *
  4192. datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
  4193. {
  4194. PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
  4195. return Py_NewRef(result);
  4196. }
  4197. static PyObject *
  4198. datetime_fold(PyDateTime_DateTime *self, void *unused)
  4199. {
  4200. return PyLong_FromLong(DATE_GET_FOLD(self));
  4201. }
  4202. static PyGetSetDef datetime_getset[] = {
  4203. {"hour", (getter)datetime_hour},
  4204. {"minute", (getter)datetime_minute},
  4205. {"second", (getter)datetime_second},
  4206. {"microsecond", (getter)datetime_microsecond},
  4207. {"tzinfo", (getter)datetime_tzinfo},
  4208. {"fold", (getter)datetime_fold},
  4209. {NULL}
  4210. };
  4211. /*
  4212. * Constructors.
  4213. */
  4214. static char *datetime_kws[] = {
  4215. "year", "month", "day", "hour", "minute", "second",
  4216. "microsecond", "tzinfo", "fold", NULL
  4217. };
  4218. static PyObject *
  4219. datetime_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
  4220. {
  4221. PyDateTime_DateTime *me;
  4222. char aware = (char)(tzinfo != Py_None);
  4223. if (aware && check_tzinfo_subclass(tzinfo) < 0) {
  4224. PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
  4225. return NULL;
  4226. }
  4227. me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
  4228. if (me != NULL) {
  4229. const char *pdata = PyBytes_AS_STRING(state);
  4230. memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
  4231. me->hashcode = -1;
  4232. me->hastzinfo = aware;
  4233. if (aware) {
  4234. me->tzinfo = Py_NewRef(tzinfo);
  4235. }
  4236. if (pdata[2] & (1 << 7)) {
  4237. me->data[2] -= 128;
  4238. me->fold = 1;
  4239. }
  4240. else {
  4241. me->fold = 0;
  4242. }
  4243. }
  4244. return (PyObject *)me;
  4245. }
  4246. static PyObject *
  4247. datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  4248. {
  4249. PyObject *self = NULL;
  4250. int year;
  4251. int month;
  4252. int day;
  4253. int hour = 0;
  4254. int minute = 0;
  4255. int second = 0;
  4256. int usecond = 0;
  4257. int fold = 0;
  4258. PyObject *tzinfo = Py_None;
  4259. /* Check for invocation from pickle with __getstate__ state */
  4260. if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
  4261. PyObject *state = PyTuple_GET_ITEM(args, 0);
  4262. if (PyTuple_GET_SIZE(args) == 2) {
  4263. tzinfo = PyTuple_GET_ITEM(args, 1);
  4264. }
  4265. if (PyBytes_Check(state)) {
  4266. if (PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
  4267. MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
  4268. {
  4269. return datetime_from_pickle(type, state, tzinfo);
  4270. }
  4271. }
  4272. else if (PyUnicode_Check(state)) {
  4273. if (PyUnicode_READY(state)) {
  4274. return NULL;
  4275. }
  4276. if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATETIME_DATASIZE &&
  4277. MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2) & 0x7F))
  4278. {
  4279. state = PyUnicode_AsLatin1String(state);
  4280. if (state == NULL) {
  4281. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
  4282. /* More informative error message. */
  4283. PyErr_SetString(PyExc_ValueError,
  4284. "Failed to encode latin1 string when unpickling "
  4285. "a datetime object. "
  4286. "pickle.load(data, encoding='latin1') is assumed.");
  4287. }
  4288. return NULL;
  4289. }
  4290. self = datetime_from_pickle(type, state, tzinfo);
  4291. Py_DECREF(state);
  4292. return self;
  4293. }
  4294. }
  4295. tzinfo = Py_None;
  4296. }
  4297. if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
  4298. &year, &month, &day, &hour, &minute,
  4299. &second, &usecond, &tzinfo, &fold)) {
  4300. self = new_datetime_ex2(year, month, day,
  4301. hour, minute, second, usecond,
  4302. tzinfo, fold, type);
  4303. }
  4304. return self;
  4305. }
  4306. /* TM_FUNC is the shared type of _PyTime_localtime() and
  4307. * _PyTime_gmtime(). */
  4308. typedef int (*TM_FUNC)(time_t timer, struct tm*);
  4309. /* As of version 2015f max fold in IANA database is
  4310. * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
  4311. static long long max_fold_seconds = 24 * 3600;
  4312. /* NB: date(1970,1,1).toordinal() == 719163 */
  4313. static long long epoch = 719163LL * 24 * 60 * 60;
  4314. static long long
  4315. utc_to_seconds(int year, int month, int day,
  4316. int hour, int minute, int second)
  4317. {
  4318. long long ordinal;
  4319. /* ymd_to_ord() doesn't support year <= 0 */
  4320. if (year < MINYEAR || year > MAXYEAR) {
  4321. PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
  4322. return -1;
  4323. }
  4324. ordinal = ymd_to_ord(year, month, day);
  4325. return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
  4326. }
  4327. static long long
  4328. local(long long u)
  4329. {
  4330. struct tm local_time;
  4331. time_t t;
  4332. u -= epoch;
  4333. t = u;
  4334. if (t != u) {
  4335. PyErr_SetString(PyExc_OverflowError,
  4336. "timestamp out of range for platform time_t");
  4337. return -1;
  4338. }
  4339. if (_PyTime_localtime(t, &local_time) != 0)
  4340. return -1;
  4341. return utc_to_seconds(local_time.tm_year + 1900,
  4342. local_time.tm_mon + 1,
  4343. local_time.tm_mday,
  4344. local_time.tm_hour,
  4345. local_time.tm_min,
  4346. local_time.tm_sec);
  4347. }
  4348. /* Internal helper.
  4349. * Build datetime from a time_t and a distinct count of microseconds.
  4350. * Pass localtime or gmtime for f, to control the interpretation of timet.
  4351. */
  4352. static PyObject *
  4353. datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
  4354. PyObject *tzinfo)
  4355. {
  4356. struct tm tm;
  4357. int year, month, day, hour, minute, second, fold = 0;
  4358. if (f(timet, &tm) != 0)
  4359. return NULL;
  4360. year = tm.tm_year + 1900;
  4361. month = tm.tm_mon + 1;
  4362. day = tm.tm_mday;
  4363. hour = tm.tm_hour;
  4364. minute = tm.tm_min;
  4365. /* The platform localtime/gmtime may insert leap seconds,
  4366. * indicated by tm.tm_sec > 59. We don't care about them,
  4367. * except to the extent that passing them on to the datetime
  4368. * constructor would raise ValueError for a reason that
  4369. * made no sense to the user.
  4370. */
  4371. second = Py_MIN(59, tm.tm_sec);
  4372. /* local timezone requires to compute fold */
  4373. if (tzinfo == Py_None && f == _PyTime_localtime
  4374. /* On Windows, passing a negative value to local results
  4375. * in an OSError because localtime_s on Windows does
  4376. * not support negative timestamps. Unfortunately this
  4377. * means that fold detection for time values between
  4378. * 0 and max_fold_seconds will result in an identical
  4379. * error since we subtract max_fold_seconds to detect a
  4380. * fold. However, since we know there haven't been any
  4381. * folds in the interval [0, max_fold_seconds) in any
  4382. * timezone, we can hackily just forego fold detection
  4383. * for this time range.
  4384. */
  4385. #ifdef MS_WINDOWS
  4386. && (timet - max_fold_seconds > 0)
  4387. #endif
  4388. ) {
  4389. long long probe_seconds, result_seconds, transition;
  4390. result_seconds = utc_to_seconds(year, month, day,
  4391. hour, minute, second);
  4392. if (result_seconds == -1 && PyErr_Occurred()) {
  4393. return NULL;
  4394. }
  4395. /* Probe max_fold_seconds to detect a fold. */
  4396. probe_seconds = local(epoch + timet - max_fold_seconds);
  4397. if (probe_seconds == -1)
  4398. return NULL;
  4399. transition = result_seconds - probe_seconds - max_fold_seconds;
  4400. if (transition < 0) {
  4401. probe_seconds = local(epoch + timet + transition);
  4402. if (probe_seconds == -1)
  4403. return NULL;
  4404. if (probe_seconds == result_seconds)
  4405. fold = 1;
  4406. }
  4407. }
  4408. return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
  4409. second, us, tzinfo, fold, cls);
  4410. }
  4411. /* Internal helper.
  4412. * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
  4413. * to control the interpretation of the timestamp. Since a double doesn't
  4414. * have enough bits to cover a datetime's full range of precision, it's
  4415. * better to call datetime_from_timet_and_us provided you have a way
  4416. * to get that much precision (e.g., C time() isn't good enough).
  4417. */
  4418. static PyObject *
  4419. datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
  4420. PyObject *tzinfo)
  4421. {
  4422. time_t timet;
  4423. long us;
  4424. if (_PyTime_ObjectToTimeval(timestamp,
  4425. &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
  4426. return NULL;
  4427. return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
  4428. }
  4429. /* Internal helper.
  4430. * Build most accurate possible datetime for current time. Pass localtime or
  4431. * gmtime for f as appropriate.
  4432. */
  4433. static PyObject *
  4434. datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
  4435. {
  4436. _PyTime_t ts = _PyTime_GetSystemClock();
  4437. time_t secs;
  4438. int us;
  4439. if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
  4440. return NULL;
  4441. assert(0 <= us && us <= 999999);
  4442. return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
  4443. }
  4444. /*[clinic input]
  4445. @classmethod
  4446. datetime.datetime.now
  4447. tz: object = None
  4448. Timezone object.
  4449. Returns new datetime object representing current time local to tz.
  4450. If no tz is specified, uses local timezone.
  4451. [clinic start generated code]*/
  4452. static PyObject *
  4453. datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
  4454. /*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
  4455. {
  4456. PyObject *self;
  4457. /* Return best possible local time -- this isn't constrained by the
  4458. * precision of a timestamp.
  4459. */
  4460. if (check_tzinfo_subclass(tz) < 0)
  4461. return NULL;
  4462. self = datetime_best_possible((PyObject *)type,
  4463. tz == Py_None ? _PyTime_localtime :
  4464. _PyTime_gmtime,
  4465. tz);
  4466. if (self != NULL && tz != Py_None) {
  4467. /* Convert UTC to tzinfo's zone. */
  4468. PyObject *res = PyObject_CallMethodOneArg(tz, &_Py_ID(fromutc), self);
  4469. Py_DECREF(self);
  4470. return res;
  4471. }
  4472. return self;
  4473. }
  4474. /* Return best possible UTC time -- this isn't constrained by the
  4475. * precision of a timestamp.
  4476. */
  4477. static PyObject *
  4478. datetime_utcnow(PyObject *cls, PyObject *dummy)
  4479. {
  4480. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  4481. "datetime.datetime.utcnow() is deprecated and scheduled for removal in a "
  4482. "future version. Use timezone-aware objects to represent datetimes "
  4483. "in UTC: datetime.datetime.now(datetime.UTC).", 1))
  4484. {
  4485. return NULL;
  4486. }
  4487. return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
  4488. }
  4489. /* Return new local datetime from timestamp (Python timestamp -- a double). */
  4490. static PyObject *
  4491. datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
  4492. {
  4493. PyObject *self;
  4494. PyObject *timestamp;
  4495. PyObject *tzinfo = Py_None;
  4496. static char *keywords[] = {"timestamp", "tz", NULL};
  4497. if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
  4498. keywords, &timestamp, &tzinfo))
  4499. return NULL;
  4500. if (check_tzinfo_subclass(tzinfo) < 0)
  4501. return NULL;
  4502. self = datetime_from_timestamp(cls,
  4503. tzinfo == Py_None ? _PyTime_localtime :
  4504. _PyTime_gmtime,
  4505. timestamp,
  4506. tzinfo);
  4507. if (self != NULL && tzinfo != Py_None) {
  4508. /* Convert UTC to tzinfo's zone. */
  4509. PyObject *res = PyObject_CallMethodOneArg(tzinfo, &_Py_ID(fromutc), self);
  4510. Py_DECREF(self);
  4511. return res;
  4512. }
  4513. return self;
  4514. }
  4515. /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
  4516. static PyObject *
  4517. datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
  4518. {
  4519. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  4520. "datetime.datetime.utcfromtimestamp() is deprecated and scheduled for removal "
  4521. "in a future version. Use timezone-aware objects to represent "
  4522. "datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).", 1))
  4523. {
  4524. return NULL;
  4525. }
  4526. PyObject *timestamp;
  4527. PyObject *result = NULL;
  4528. if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
  4529. result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
  4530. Py_None);
  4531. return result;
  4532. }
  4533. /* Return new datetime from _strptime.strptime_datetime(). */
  4534. static PyObject *
  4535. datetime_strptime(PyObject *cls, PyObject *args)
  4536. {
  4537. PyObject *string, *format, *result;
  4538. if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
  4539. return NULL;
  4540. PyObject *module = PyImport_ImportModule("_strptime");
  4541. if (module == NULL) {
  4542. return NULL;
  4543. }
  4544. result = PyObject_CallMethodObjArgs(module, &_Py_ID(_strptime_datetime),
  4545. cls, string, format, NULL);
  4546. Py_DECREF(module);
  4547. return result;
  4548. }
  4549. /* Return new datetime from date/datetime and time arguments. */
  4550. static PyObject *
  4551. datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
  4552. {
  4553. static char *keywords[] = {"date", "time", "tzinfo", NULL};
  4554. PyObject *date;
  4555. PyObject *time;
  4556. PyObject *tzinfo = NULL;
  4557. PyObject *result = NULL;
  4558. if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
  4559. &PyDateTime_DateType, &date,
  4560. &PyDateTime_TimeType, &time, &tzinfo)) {
  4561. if (tzinfo == NULL) {
  4562. if (HASTZINFO(time))
  4563. tzinfo = ((PyDateTime_Time *)time)->tzinfo;
  4564. else
  4565. tzinfo = Py_None;
  4566. }
  4567. result = new_datetime_subclass_fold_ex(GET_YEAR(date),
  4568. GET_MONTH(date),
  4569. GET_DAY(date),
  4570. TIME_GET_HOUR(time),
  4571. TIME_GET_MINUTE(time),
  4572. TIME_GET_SECOND(time),
  4573. TIME_GET_MICROSECOND(time),
  4574. tzinfo,
  4575. TIME_GET_FOLD(time),
  4576. cls);
  4577. }
  4578. return result;
  4579. }
  4580. static PyObject *
  4581. _sanitize_isoformat_str(PyObject *dtstr)
  4582. {
  4583. Py_ssize_t len = PyUnicode_GetLength(dtstr);
  4584. if (len < 7) { // All valid ISO 8601 strings are at least 7 characters long
  4585. return NULL;
  4586. }
  4587. // `fromisoformat` allows surrogate characters in exactly one position,
  4588. // the separator; to allow datetime_fromisoformat to make the simplifying
  4589. // assumption that all valid strings can be encoded in UTF-8, this function
  4590. // replaces any surrogate character separators with `T`.
  4591. //
  4592. // The result of this, if not NULL, returns a new reference
  4593. const void* const unicode_data = PyUnicode_DATA(dtstr);
  4594. const int kind = PyUnicode_KIND(dtstr);
  4595. // Depending on the format of the string, the separator can only ever be
  4596. // in positions 7, 8 or 10. We'll check each of these for a surrogate and
  4597. // if we find one, replace it with `T`. If there is more than one surrogate,
  4598. // we don't have to bother sanitizing it, because the function will later
  4599. // fail when we try to encode the string as ASCII.
  4600. static const size_t potential_separators[3] = {7, 8, 10};
  4601. size_t surrogate_separator = 0;
  4602. for(size_t idx = 0;
  4603. idx < sizeof(potential_separators) / sizeof(*potential_separators);
  4604. ++idx) {
  4605. size_t pos = potential_separators[idx];
  4606. if (pos > (size_t)len) {
  4607. break;
  4608. }
  4609. if(Py_UNICODE_IS_SURROGATE(PyUnicode_READ(kind, unicode_data, pos))) {
  4610. surrogate_separator = pos;
  4611. break;
  4612. }
  4613. }
  4614. if (surrogate_separator == 0) {
  4615. return Py_NewRef(dtstr);
  4616. }
  4617. PyObject *str_out = _PyUnicode_Copy(dtstr);
  4618. if (str_out == NULL) {
  4619. return NULL;
  4620. }
  4621. if (PyUnicode_WriteChar(str_out, surrogate_separator, (Py_UCS4)'T')) {
  4622. Py_DECREF(str_out);
  4623. return NULL;
  4624. }
  4625. return str_out;
  4626. }
  4627. static Py_ssize_t
  4628. _find_isoformat_datetime_separator(const char *dtstr, Py_ssize_t len) {
  4629. // The valid date formats can all be distinguished by characters 4 and 5
  4630. // and further narrowed down by character
  4631. // which tells us where to look for the separator character.
  4632. // Format | As-rendered | Position
  4633. // ---------------------------------------
  4634. // %Y-%m-%d | YYYY-MM-DD | 10
  4635. // %Y%m%d | YYYYMMDD | 8
  4636. // %Y-W%V | YYYY-Www | 8
  4637. // %YW%V | YYYYWww | 7
  4638. // %Y-W%V-%u | YYYY-Www-d | 10
  4639. // %YW%V%u | YYYYWwwd | 8
  4640. // %Y-%j | YYYY-DDD | 8
  4641. // %Y%j | YYYYDDD | 7
  4642. //
  4643. // Note that because we allow *any* character for the separator, in the
  4644. // case where character 4 is W, it's not straightforward to determine where
  4645. // the separator is — in the case of YYYY-Www-d, you have actual ambiguity,
  4646. // e.g. 2020-W01-0000 could be YYYY-Www-D0HH or YYYY-Www-HHMM, when the
  4647. // separator character is a number in the former case or a hyphen in the
  4648. // latter case.
  4649. //
  4650. // The case of YYYYWww can be distinguished from YYYYWwwd by tracking ahead
  4651. // to either the end of the string or the first non-numeric character —
  4652. // since the time components all come in pairs YYYYWww#HH can be
  4653. // distinguished from YYYYWwwd#HH by the fact that there will always be an
  4654. // odd number of digits before the first non-digit character in the former
  4655. // case.
  4656. static const char date_separator = '-';
  4657. static const char week_indicator = 'W';
  4658. if (len == 7) {
  4659. return 7;
  4660. }
  4661. if (dtstr[4] == date_separator) {
  4662. // YYYY-???
  4663. if (dtstr[5] == week_indicator) {
  4664. // YYYY-W??
  4665. if (len < 8) {
  4666. return -1;
  4667. }
  4668. if (len > 8 && dtstr[8] == date_separator) {
  4669. // YYYY-Www-D (10) or YYYY-Www-HH (8)
  4670. if (len == 9) { return -1; }
  4671. if (len > 10 && is_digit(dtstr[10])) {
  4672. // This is as far as we'll try to go to resolve the
  4673. // ambiguity for the moment — if we have YYYY-Www-##, the
  4674. // separator is either a hyphen at 8 or a number at 10.
  4675. //
  4676. // We'll assume it's a hyphen at 8 because it's way more
  4677. // likely that someone will use a hyphen as a separator
  4678. // than a number, but at this point it's really best effort
  4679. // because this is an extension of the spec anyway.
  4680. return 8;
  4681. }
  4682. return 10;
  4683. } else {
  4684. // YYYY-Www (8)
  4685. return 8;
  4686. }
  4687. } else {
  4688. // YYYY-MM-DD (10)
  4689. return 10;
  4690. }
  4691. } else {
  4692. // YYYY???
  4693. if (dtstr[4] == week_indicator) {
  4694. // YYYYWww (7) or YYYYWwwd (8)
  4695. size_t idx = 7;
  4696. for (; idx < (size_t)len; ++idx) {
  4697. // Keep going until we run out of digits.
  4698. if (!is_digit(dtstr[idx])) {
  4699. break;
  4700. }
  4701. }
  4702. if (idx < 9) {
  4703. return idx;
  4704. }
  4705. if (idx % 2 == 0) {
  4706. // If the index of the last number is even, it's YYYYWww
  4707. return 7;
  4708. } else {
  4709. return 8;
  4710. }
  4711. } else {
  4712. // YYYYMMDD (8)
  4713. return 8;
  4714. }
  4715. }
  4716. }
  4717. static PyObject *
  4718. datetime_fromisoformat(PyObject *cls, PyObject *dtstr)
  4719. {
  4720. assert(dtstr != NULL);
  4721. if (!PyUnicode_Check(dtstr)) {
  4722. PyErr_SetString(PyExc_TypeError,
  4723. "fromisoformat: argument must be str");
  4724. return NULL;
  4725. }
  4726. // We only need to sanitize this string if the separator is a surrogate
  4727. // character. In the situation where the separator location is ambiguous,
  4728. // we don't have to sanitize it anything because that can only happen when
  4729. // the separator is either '-' or a number. This should mostly be a noop
  4730. // but it makes the reference counting easier if we still sanitize.
  4731. PyObject *dtstr_clean = _sanitize_isoformat_str(dtstr);
  4732. if (dtstr_clean == NULL) {
  4733. goto invalid_string_error;
  4734. }
  4735. Py_ssize_t len;
  4736. const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr_clean, &len);
  4737. if (dt_ptr == NULL) {
  4738. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
  4739. // Encoding errors are invalid string errors at this point
  4740. goto invalid_string_error;
  4741. }
  4742. else {
  4743. goto error;
  4744. }
  4745. }
  4746. const Py_ssize_t separator_location = _find_isoformat_datetime_separator(
  4747. dt_ptr, len);
  4748. const char *p = dt_ptr;
  4749. int year = 0, month = 0, day = 0;
  4750. int hour = 0, minute = 0, second = 0, microsecond = 0;
  4751. int tzoffset = 0, tzusec = 0;
  4752. // date runs up to separator_location
  4753. int rv = parse_isoformat_date(p, separator_location, &year, &month, &day);
  4754. if (!rv && len > separator_location) {
  4755. // In UTF-8, the length of multi-byte characters is encoded in the MSB
  4756. p += separator_location;
  4757. if ((p[0] & 0x80) == 0) {
  4758. p += 1;
  4759. }
  4760. else {
  4761. switch (p[0] & 0xf0) {
  4762. case 0xe0:
  4763. p += 3;
  4764. break;
  4765. case 0xf0:
  4766. p += 4;
  4767. break;
  4768. default:
  4769. p += 2;
  4770. break;
  4771. }
  4772. }
  4773. len -= (p - dt_ptr);
  4774. rv = parse_isoformat_time(p, len, &hour, &minute, &second,
  4775. &microsecond, &tzoffset, &tzusec);
  4776. }
  4777. if (rv < 0) {
  4778. goto invalid_string_error;
  4779. }
  4780. PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset, tzusec);
  4781. if (tzinfo == NULL) {
  4782. goto error;
  4783. }
  4784. PyObject *dt = new_datetime_subclass_ex(year, month, day, hour, minute,
  4785. second, microsecond, tzinfo, cls);
  4786. Py_DECREF(tzinfo);
  4787. Py_DECREF(dtstr_clean);
  4788. return dt;
  4789. invalid_string_error:
  4790. PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
  4791. error:
  4792. Py_XDECREF(dtstr_clean);
  4793. return NULL;
  4794. }
  4795. /*
  4796. * Destructor.
  4797. */
  4798. static void
  4799. datetime_dealloc(PyDateTime_DateTime *self)
  4800. {
  4801. if (HASTZINFO(self)) {
  4802. Py_XDECREF(self->tzinfo);
  4803. }
  4804. Py_TYPE(self)->tp_free((PyObject *)self);
  4805. }
  4806. /*
  4807. * Indirect access to tzinfo methods.
  4808. */
  4809. /* These are all METH_NOARGS, so don't need to check the arglist. */
  4810. static PyObject *
  4811. datetime_utcoffset(PyObject *self, PyObject *unused) {
  4812. return call_utcoffset(GET_DT_TZINFO(self), self);
  4813. }
  4814. static PyObject *
  4815. datetime_dst(PyObject *self, PyObject *unused) {
  4816. return call_dst(GET_DT_TZINFO(self), self);
  4817. }
  4818. static PyObject *
  4819. datetime_tzname(PyObject *self, PyObject *unused) {
  4820. return call_tzname(GET_DT_TZINFO(self), self);
  4821. }
  4822. /*
  4823. * datetime arithmetic.
  4824. */
  4825. /* factor must be 1 (to add) or -1 (to subtract). The result inherits
  4826. * the tzinfo state of date.
  4827. */
  4828. static PyObject *
  4829. add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
  4830. int factor)
  4831. {
  4832. /* Note that the C-level additions can't overflow, because of
  4833. * invariant bounds on the member values.
  4834. */
  4835. int year = GET_YEAR(date);
  4836. int month = GET_MONTH(date);
  4837. int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
  4838. int hour = DATE_GET_HOUR(date);
  4839. int minute = DATE_GET_MINUTE(date);
  4840. int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
  4841. int microsecond = DATE_GET_MICROSECOND(date) +
  4842. GET_TD_MICROSECONDS(delta) * factor;
  4843. assert(factor == 1 || factor == -1);
  4844. if (normalize_datetime(&year, &month, &day,
  4845. &hour, &minute, &second, &microsecond) < 0) {
  4846. return NULL;
  4847. }
  4848. return new_datetime_subclass_ex(year, month, day,
  4849. hour, minute, second, microsecond,
  4850. HASTZINFO(date) ? date->tzinfo : Py_None,
  4851. (PyObject *)Py_TYPE(date));
  4852. }
  4853. static PyObject *
  4854. datetime_add(PyObject *left, PyObject *right)
  4855. {
  4856. if (PyDateTime_Check(left)) {
  4857. /* datetime + ??? */
  4858. if (PyDelta_Check(right))
  4859. /* datetime + delta */
  4860. return add_datetime_timedelta(
  4861. (PyDateTime_DateTime *)left,
  4862. (PyDateTime_Delta *)right,
  4863. 1);
  4864. }
  4865. else if (PyDelta_Check(left)) {
  4866. /* delta + datetime */
  4867. return add_datetime_timedelta((PyDateTime_DateTime *) right,
  4868. (PyDateTime_Delta *) left,
  4869. 1);
  4870. }
  4871. Py_RETURN_NOTIMPLEMENTED;
  4872. }
  4873. static PyObject *
  4874. datetime_subtract(PyObject *left, PyObject *right)
  4875. {
  4876. PyObject *result = Py_NotImplemented;
  4877. if (PyDateTime_Check(left)) {
  4878. /* datetime - ??? */
  4879. if (PyDateTime_Check(right)) {
  4880. /* datetime - datetime */
  4881. PyObject *offset1, *offset2, *offdiff = NULL;
  4882. int delta_d, delta_s, delta_us;
  4883. if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
  4884. offset1 = Py_NewRef(Py_None);
  4885. offset2 = Py_NewRef(Py_None);
  4886. }
  4887. else {
  4888. offset1 = datetime_utcoffset(left, NULL);
  4889. if (offset1 == NULL)
  4890. return NULL;
  4891. offset2 = datetime_utcoffset(right, NULL);
  4892. if (offset2 == NULL) {
  4893. Py_DECREF(offset1);
  4894. return NULL;
  4895. }
  4896. if ((offset1 != Py_None) != (offset2 != Py_None)) {
  4897. PyErr_SetString(PyExc_TypeError,
  4898. "can't subtract offset-naive and "
  4899. "offset-aware datetimes");
  4900. Py_DECREF(offset1);
  4901. Py_DECREF(offset2);
  4902. return NULL;
  4903. }
  4904. }
  4905. if ((offset1 != offset2) &&
  4906. delta_cmp(offset1, offset2) != 0) {
  4907. offdiff = delta_subtract(offset1, offset2);
  4908. if (offdiff == NULL) {
  4909. Py_DECREF(offset1);
  4910. Py_DECREF(offset2);
  4911. return NULL;
  4912. }
  4913. }
  4914. Py_DECREF(offset1);
  4915. Py_DECREF(offset2);
  4916. delta_d = ymd_to_ord(GET_YEAR(left),
  4917. GET_MONTH(left),
  4918. GET_DAY(left)) -
  4919. ymd_to_ord(GET_YEAR(right),
  4920. GET_MONTH(right),
  4921. GET_DAY(right));
  4922. /* These can't overflow, since the values are
  4923. * normalized. At most this gives the number of
  4924. * seconds in one day.
  4925. */
  4926. delta_s = (DATE_GET_HOUR(left) -
  4927. DATE_GET_HOUR(right)) * 3600 +
  4928. (DATE_GET_MINUTE(left) -
  4929. DATE_GET_MINUTE(right)) * 60 +
  4930. (DATE_GET_SECOND(left) -
  4931. DATE_GET_SECOND(right));
  4932. delta_us = DATE_GET_MICROSECOND(left) -
  4933. DATE_GET_MICROSECOND(right);
  4934. result = new_delta(delta_d, delta_s, delta_us, 1);
  4935. if (result == NULL)
  4936. return NULL;
  4937. if (offdiff != NULL) {
  4938. Py_SETREF(result, delta_subtract(result, offdiff));
  4939. Py_DECREF(offdiff);
  4940. }
  4941. }
  4942. else if (PyDelta_Check(right)) {
  4943. /* datetime - delta */
  4944. result = add_datetime_timedelta(
  4945. (PyDateTime_DateTime *)left,
  4946. (PyDateTime_Delta *)right,
  4947. -1);
  4948. }
  4949. }
  4950. if (result == Py_NotImplemented)
  4951. Py_INCREF(result);
  4952. return result;
  4953. }
  4954. /* Various ways to turn a datetime into a string. */
  4955. static PyObject *
  4956. datetime_repr(PyDateTime_DateTime *self)
  4957. {
  4958. const char *type_name = Py_TYPE(self)->tp_name;
  4959. PyObject *baserepr;
  4960. if (DATE_GET_MICROSECOND(self)) {
  4961. baserepr = PyUnicode_FromFormat(
  4962. "%s(%d, %d, %d, %d, %d, %d, %d)",
  4963. type_name,
  4964. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  4965. DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
  4966. DATE_GET_SECOND(self),
  4967. DATE_GET_MICROSECOND(self));
  4968. }
  4969. else if (DATE_GET_SECOND(self)) {
  4970. baserepr = PyUnicode_FromFormat(
  4971. "%s(%d, %d, %d, %d, %d, %d)",
  4972. type_name,
  4973. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  4974. DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
  4975. DATE_GET_SECOND(self));
  4976. }
  4977. else {
  4978. baserepr = PyUnicode_FromFormat(
  4979. "%s(%d, %d, %d, %d, %d)",
  4980. type_name,
  4981. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  4982. DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
  4983. }
  4984. if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
  4985. baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
  4986. if (baserepr == NULL || ! HASTZINFO(self))
  4987. return baserepr;
  4988. return append_keyword_tzinfo(baserepr, self->tzinfo);
  4989. }
  4990. static PyObject *
  4991. datetime_str(PyDateTime_DateTime *self)
  4992. {
  4993. PyObject *space = PyUnicode_FromString(" ");
  4994. if (space == NULL) {
  4995. return NULL;
  4996. }
  4997. PyObject *res = PyObject_CallMethodOneArg((PyObject *)self,
  4998. &_Py_ID(isoformat), space);
  4999. Py_DECREF(space);
  5000. return res;
  5001. }
  5002. static PyObject *
  5003. datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  5004. {
  5005. int sep = 'T';
  5006. char *timespec = NULL;
  5007. static char *keywords[] = {"sep", "timespec", NULL};
  5008. char buffer[100];
  5009. PyObject *result = NULL;
  5010. int us = DATE_GET_MICROSECOND(self);
  5011. static const char *specs[][2] = {
  5012. {"hours", "%04d-%02d-%02d%c%02d"},
  5013. {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
  5014. {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
  5015. {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
  5016. {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
  5017. };
  5018. size_t given_spec;
  5019. if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
  5020. return NULL;
  5021. if (timespec == NULL || strcmp(timespec, "auto") == 0) {
  5022. if (us == 0) {
  5023. /* seconds */
  5024. given_spec = 2;
  5025. }
  5026. else {
  5027. /* microseconds */
  5028. given_spec = 4;
  5029. }
  5030. }
  5031. else {
  5032. for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
  5033. if (strcmp(timespec, specs[given_spec][0]) == 0) {
  5034. if (given_spec == 3) {
  5035. us = us / 1000;
  5036. }
  5037. break;
  5038. }
  5039. }
  5040. }
  5041. if (given_spec == Py_ARRAY_LENGTH(specs)) {
  5042. PyErr_Format(PyExc_ValueError, "Unknown timespec value");
  5043. return NULL;
  5044. }
  5045. else {
  5046. result = PyUnicode_FromFormat(specs[given_spec][1],
  5047. GET_YEAR(self), GET_MONTH(self),
  5048. GET_DAY(self), (int)sep,
  5049. DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
  5050. DATE_GET_SECOND(self), us);
  5051. }
  5052. if (!result || !HASTZINFO(self))
  5053. return result;
  5054. /* We need to append the UTC offset. */
  5055. if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
  5056. (PyObject *)self) < 0) {
  5057. Py_DECREF(result);
  5058. return NULL;
  5059. }
  5060. PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
  5061. return result;
  5062. }
  5063. static PyObject *
  5064. datetime_ctime(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5065. {
  5066. return format_ctime((PyDateTime_Date *)self,
  5067. DATE_GET_HOUR(self),
  5068. DATE_GET_MINUTE(self),
  5069. DATE_GET_SECOND(self));
  5070. }
  5071. /* Miscellaneous methods. */
  5072. static PyObject *
  5073. flip_fold(PyObject *dt)
  5074. {
  5075. return new_datetime_ex2(GET_YEAR(dt),
  5076. GET_MONTH(dt),
  5077. GET_DAY(dt),
  5078. DATE_GET_HOUR(dt),
  5079. DATE_GET_MINUTE(dt),
  5080. DATE_GET_SECOND(dt),
  5081. DATE_GET_MICROSECOND(dt),
  5082. HASTZINFO(dt) ?
  5083. ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
  5084. !DATE_GET_FOLD(dt),
  5085. Py_TYPE(dt));
  5086. }
  5087. static PyObject *
  5088. get_flip_fold_offset(PyObject *dt)
  5089. {
  5090. PyObject *result, *flip_dt;
  5091. flip_dt = flip_fold(dt);
  5092. if (flip_dt == NULL)
  5093. return NULL;
  5094. result = datetime_utcoffset(flip_dt, NULL);
  5095. Py_DECREF(flip_dt);
  5096. return result;
  5097. }
  5098. /* PEP 495 exception: Whenever one or both of the operands in
  5099. * inter-zone comparison is such that its utcoffset() depends
  5100. * on the value of its fold attribute, the result is False.
  5101. *
  5102. * Return 1 if exception applies, 0 if not, and -1 on error.
  5103. */
  5104. static int
  5105. pep495_eq_exception(PyObject *self, PyObject *other,
  5106. PyObject *offset_self, PyObject *offset_other)
  5107. {
  5108. int result = 0;
  5109. PyObject *flip_offset;
  5110. flip_offset = get_flip_fold_offset(self);
  5111. if (flip_offset == NULL)
  5112. return -1;
  5113. if (flip_offset != offset_self &&
  5114. delta_cmp(flip_offset, offset_self))
  5115. {
  5116. result = 1;
  5117. goto done;
  5118. }
  5119. Py_DECREF(flip_offset);
  5120. flip_offset = get_flip_fold_offset(other);
  5121. if (flip_offset == NULL)
  5122. return -1;
  5123. if (flip_offset != offset_other &&
  5124. delta_cmp(flip_offset, offset_other))
  5125. result = 1;
  5126. done:
  5127. Py_DECREF(flip_offset);
  5128. return result;
  5129. }
  5130. static PyObject *
  5131. datetime_richcompare(PyObject *self, PyObject *other, int op)
  5132. {
  5133. PyObject *result = NULL;
  5134. PyObject *offset1, *offset2;
  5135. int diff;
  5136. if (! PyDateTime_Check(other)) {
  5137. if (PyDate_Check(other)) {
  5138. /* Prevent invocation of date_richcompare. We want to
  5139. return NotImplemented here to give the other object
  5140. a chance. But since DateTime is a subclass of
  5141. Date, if the other object is a Date, it would
  5142. compute an ordering based on the date part alone,
  5143. and we don't want that. So force unequal or
  5144. uncomparable here in that case. */
  5145. if (op == Py_EQ)
  5146. Py_RETURN_FALSE;
  5147. if (op == Py_NE)
  5148. Py_RETURN_TRUE;
  5149. return cmperror(self, other);
  5150. }
  5151. Py_RETURN_NOTIMPLEMENTED;
  5152. }
  5153. if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
  5154. diff = memcmp(((PyDateTime_DateTime *)self)->data,
  5155. ((PyDateTime_DateTime *)other)->data,
  5156. _PyDateTime_DATETIME_DATASIZE);
  5157. return diff_to_bool(diff, op);
  5158. }
  5159. offset1 = datetime_utcoffset(self, NULL);
  5160. if (offset1 == NULL)
  5161. return NULL;
  5162. offset2 = datetime_utcoffset(other, NULL);
  5163. if (offset2 == NULL)
  5164. goto done;
  5165. /* If they're both naive, or both aware and have the same offsets,
  5166. * we get off cheap. Note that if they're both naive, offset1 ==
  5167. * offset2 == Py_None at this point.
  5168. */
  5169. if ((offset1 == offset2) ||
  5170. (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
  5171. delta_cmp(offset1, offset2) == 0)) {
  5172. diff = memcmp(((PyDateTime_DateTime *)self)->data,
  5173. ((PyDateTime_DateTime *)other)->data,
  5174. _PyDateTime_DATETIME_DATASIZE);
  5175. if ((op == Py_EQ || op == Py_NE) && diff == 0) {
  5176. int ex = pep495_eq_exception(self, other, offset1, offset2);
  5177. if (ex == -1)
  5178. goto done;
  5179. if (ex)
  5180. diff = 1;
  5181. }
  5182. result = diff_to_bool(diff, op);
  5183. }
  5184. else if (offset1 != Py_None && offset2 != Py_None) {
  5185. PyDateTime_Delta *delta;
  5186. assert(offset1 != offset2); /* else last "if" handled it */
  5187. delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
  5188. other);
  5189. if (delta == NULL)
  5190. goto done;
  5191. diff = GET_TD_DAYS(delta);
  5192. if (diff == 0)
  5193. diff = GET_TD_SECONDS(delta) |
  5194. GET_TD_MICROSECONDS(delta);
  5195. Py_DECREF(delta);
  5196. if ((op == Py_EQ || op == Py_NE) && diff == 0) {
  5197. int ex = pep495_eq_exception(self, other, offset1, offset2);
  5198. if (ex == -1)
  5199. goto done;
  5200. if (ex)
  5201. diff = 1;
  5202. }
  5203. result = diff_to_bool(diff, op);
  5204. }
  5205. else if (op == Py_EQ) {
  5206. result = Py_NewRef(Py_False);
  5207. }
  5208. else if (op == Py_NE) {
  5209. result = Py_NewRef(Py_True);
  5210. }
  5211. else {
  5212. PyErr_SetString(PyExc_TypeError,
  5213. "can't compare offset-naive and "
  5214. "offset-aware datetimes");
  5215. }
  5216. done:
  5217. Py_DECREF(offset1);
  5218. Py_XDECREF(offset2);
  5219. return result;
  5220. }
  5221. static Py_hash_t
  5222. datetime_hash(PyDateTime_DateTime *self)
  5223. {
  5224. if (self->hashcode == -1) {
  5225. PyObject *offset, *self0;
  5226. if (DATE_GET_FOLD(self)) {
  5227. self0 = new_datetime_ex2(GET_YEAR(self),
  5228. GET_MONTH(self),
  5229. GET_DAY(self),
  5230. DATE_GET_HOUR(self),
  5231. DATE_GET_MINUTE(self),
  5232. DATE_GET_SECOND(self),
  5233. DATE_GET_MICROSECOND(self),
  5234. HASTZINFO(self) ? self->tzinfo : Py_None,
  5235. 0, Py_TYPE(self));
  5236. if (self0 == NULL)
  5237. return -1;
  5238. }
  5239. else {
  5240. self0 = Py_NewRef(self);
  5241. }
  5242. offset = datetime_utcoffset(self0, NULL);
  5243. Py_DECREF(self0);
  5244. if (offset == NULL)
  5245. return -1;
  5246. /* Reduce this to a hash of another object. */
  5247. if (offset == Py_None)
  5248. self->hashcode = generic_hash(
  5249. (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
  5250. else {
  5251. PyObject *temp1, *temp2;
  5252. int days, seconds;
  5253. assert(HASTZINFO(self));
  5254. days = ymd_to_ord(GET_YEAR(self),
  5255. GET_MONTH(self),
  5256. GET_DAY(self));
  5257. seconds = DATE_GET_HOUR(self) * 3600 +
  5258. DATE_GET_MINUTE(self) * 60 +
  5259. DATE_GET_SECOND(self);
  5260. temp1 = new_delta(days, seconds,
  5261. DATE_GET_MICROSECOND(self),
  5262. 1);
  5263. if (temp1 == NULL) {
  5264. Py_DECREF(offset);
  5265. return -1;
  5266. }
  5267. temp2 = delta_subtract(temp1, offset);
  5268. Py_DECREF(temp1);
  5269. if (temp2 == NULL) {
  5270. Py_DECREF(offset);
  5271. return -1;
  5272. }
  5273. self->hashcode = PyObject_Hash(temp2);
  5274. Py_DECREF(temp2);
  5275. }
  5276. Py_DECREF(offset);
  5277. }
  5278. return self->hashcode;
  5279. }
  5280. static PyObject *
  5281. datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  5282. {
  5283. PyObject *clone;
  5284. PyObject *tuple;
  5285. int y = GET_YEAR(self);
  5286. int m = GET_MONTH(self);
  5287. int d = GET_DAY(self);
  5288. int hh = DATE_GET_HOUR(self);
  5289. int mm = DATE_GET_MINUTE(self);
  5290. int ss = DATE_GET_SECOND(self);
  5291. int us = DATE_GET_MICROSECOND(self);
  5292. PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
  5293. int fold = DATE_GET_FOLD(self);
  5294. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
  5295. datetime_kws,
  5296. &y, &m, &d, &hh, &mm, &ss, &us,
  5297. &tzinfo, &fold))
  5298. return NULL;
  5299. if (fold != 0 && fold != 1) {
  5300. PyErr_SetString(PyExc_ValueError,
  5301. "fold must be either 0 or 1");
  5302. return NULL;
  5303. }
  5304. tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
  5305. if (tuple == NULL)
  5306. return NULL;
  5307. clone = datetime_new(Py_TYPE(self), tuple, NULL);
  5308. if (clone != NULL) {
  5309. DATE_SET_FOLD(clone, fold);
  5310. }
  5311. Py_DECREF(tuple);
  5312. return clone;
  5313. }
  5314. static PyObject *
  5315. local_timezone_from_timestamp(time_t timestamp)
  5316. {
  5317. PyObject *result = NULL;
  5318. PyObject *delta;
  5319. struct tm local_time_tm;
  5320. PyObject *nameo = NULL;
  5321. const char *zone = NULL;
  5322. if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
  5323. return NULL;
  5324. #ifdef HAVE_STRUCT_TM_TM_ZONE
  5325. zone = local_time_tm.tm_zone;
  5326. delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
  5327. #else /* HAVE_STRUCT_TM_TM_ZONE */
  5328. {
  5329. PyObject *local_time, *utc_time;
  5330. struct tm utc_time_tm;
  5331. char buf[100];
  5332. strftime(buf, sizeof(buf), "%Z", &local_time_tm);
  5333. zone = buf;
  5334. local_time = new_datetime(local_time_tm.tm_year + 1900,
  5335. local_time_tm.tm_mon + 1,
  5336. local_time_tm.tm_mday,
  5337. local_time_tm.tm_hour,
  5338. local_time_tm.tm_min,
  5339. local_time_tm.tm_sec, 0, Py_None, 0);
  5340. if (local_time == NULL) {
  5341. return NULL;
  5342. }
  5343. if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
  5344. return NULL;
  5345. utc_time = new_datetime(utc_time_tm.tm_year + 1900,
  5346. utc_time_tm.tm_mon + 1,
  5347. utc_time_tm.tm_mday,
  5348. utc_time_tm.tm_hour,
  5349. utc_time_tm.tm_min,
  5350. utc_time_tm.tm_sec, 0, Py_None, 0);
  5351. if (utc_time == NULL) {
  5352. Py_DECREF(local_time);
  5353. return NULL;
  5354. }
  5355. delta = datetime_subtract(local_time, utc_time);
  5356. Py_DECREF(local_time);
  5357. Py_DECREF(utc_time);
  5358. }
  5359. #endif /* HAVE_STRUCT_TM_TM_ZONE */
  5360. if (delta == NULL) {
  5361. return NULL;
  5362. }
  5363. if (zone != NULL) {
  5364. nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
  5365. if (nameo == NULL)
  5366. goto error;
  5367. }
  5368. result = new_timezone(delta, nameo);
  5369. Py_XDECREF(nameo);
  5370. error:
  5371. Py_DECREF(delta);
  5372. return result;
  5373. }
  5374. static PyObject *
  5375. local_timezone(PyDateTime_DateTime *utc_time)
  5376. {
  5377. time_t timestamp;
  5378. PyObject *delta;
  5379. PyObject *one_second;
  5380. PyObject *seconds;
  5381. delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
  5382. if (delta == NULL)
  5383. return NULL;
  5384. one_second = new_delta(0, 1, 0, 0);
  5385. if (one_second == NULL) {
  5386. Py_DECREF(delta);
  5387. return NULL;
  5388. }
  5389. seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
  5390. (PyDateTime_Delta *)one_second);
  5391. Py_DECREF(one_second);
  5392. Py_DECREF(delta);
  5393. if (seconds == NULL)
  5394. return NULL;
  5395. timestamp = _PyLong_AsTime_t(seconds);
  5396. Py_DECREF(seconds);
  5397. if (timestamp == -1 && PyErr_Occurred())
  5398. return NULL;
  5399. return local_timezone_from_timestamp(timestamp);
  5400. }
  5401. static long long
  5402. local_to_seconds(int year, int month, int day,
  5403. int hour, int minute, int second, int fold);
  5404. static PyObject *
  5405. local_timezone_from_local(PyDateTime_DateTime *local_dt)
  5406. {
  5407. long long seconds, seconds2;
  5408. time_t timestamp;
  5409. int fold = DATE_GET_FOLD(local_dt);
  5410. seconds = local_to_seconds(GET_YEAR(local_dt),
  5411. GET_MONTH(local_dt),
  5412. GET_DAY(local_dt),
  5413. DATE_GET_HOUR(local_dt),
  5414. DATE_GET_MINUTE(local_dt),
  5415. DATE_GET_SECOND(local_dt),
  5416. fold);
  5417. if (seconds == -1)
  5418. return NULL;
  5419. seconds2 = local_to_seconds(GET_YEAR(local_dt),
  5420. GET_MONTH(local_dt),
  5421. GET_DAY(local_dt),
  5422. DATE_GET_HOUR(local_dt),
  5423. DATE_GET_MINUTE(local_dt),
  5424. DATE_GET_SECOND(local_dt),
  5425. !fold);
  5426. if (seconds2 == -1)
  5427. return NULL;
  5428. /* Detect gap */
  5429. if (seconds2 != seconds && (seconds2 > seconds) == fold)
  5430. seconds = seconds2;
  5431. /* XXX: add bounds check */
  5432. timestamp = seconds - epoch;
  5433. return local_timezone_from_timestamp(timestamp);
  5434. }
  5435. static PyDateTime_DateTime *
  5436. datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  5437. {
  5438. PyDateTime_DateTime *result;
  5439. PyObject *offset;
  5440. PyObject *temp;
  5441. PyObject *self_tzinfo;
  5442. PyObject *tzinfo = Py_None;
  5443. static char *keywords[] = {"tz", NULL};
  5444. if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
  5445. &tzinfo))
  5446. return NULL;
  5447. if (check_tzinfo_subclass(tzinfo) == -1)
  5448. return NULL;
  5449. if (!HASTZINFO(self) || self->tzinfo == Py_None) {
  5450. naive:
  5451. self_tzinfo = local_timezone_from_local(self);
  5452. if (self_tzinfo == NULL)
  5453. return NULL;
  5454. } else {
  5455. self_tzinfo = Py_NewRef(self->tzinfo);
  5456. }
  5457. /* Conversion to self's own time zone is a NOP. */
  5458. if (self_tzinfo == tzinfo) {
  5459. Py_DECREF(self_tzinfo);
  5460. return (PyDateTime_DateTime*)Py_NewRef(self);
  5461. }
  5462. /* Convert self to UTC. */
  5463. offset = call_utcoffset(self_tzinfo, (PyObject *)self);
  5464. Py_DECREF(self_tzinfo);
  5465. if (offset == NULL)
  5466. return NULL;
  5467. else if(offset == Py_None) {
  5468. Py_DECREF(offset);
  5469. goto naive;
  5470. }
  5471. else if (!PyDelta_Check(offset)) {
  5472. Py_DECREF(offset);
  5473. PyErr_Format(PyExc_TypeError, "utcoffset() returned %.200s,"
  5474. " expected timedelta or None", Py_TYPE(offset)->tp_name);
  5475. return NULL;
  5476. }
  5477. /* result = self - offset */
  5478. result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
  5479. (PyDateTime_Delta *)offset, -1);
  5480. Py_DECREF(offset);
  5481. if (result == NULL)
  5482. return NULL;
  5483. /* Make sure result is aware and UTC. */
  5484. if (!HASTZINFO(result)) {
  5485. temp = (PyObject *)result;
  5486. result = (PyDateTime_DateTime *)
  5487. new_datetime_ex2(GET_YEAR(result),
  5488. GET_MONTH(result),
  5489. GET_DAY(result),
  5490. DATE_GET_HOUR(result),
  5491. DATE_GET_MINUTE(result),
  5492. DATE_GET_SECOND(result),
  5493. DATE_GET_MICROSECOND(result),
  5494. PyDateTime_TimeZone_UTC,
  5495. DATE_GET_FOLD(result),
  5496. Py_TYPE(result));
  5497. Py_DECREF(temp);
  5498. if (result == NULL)
  5499. return NULL;
  5500. }
  5501. else {
  5502. /* Result is already aware - just replace tzinfo. */
  5503. Py_SETREF(result->tzinfo, Py_NewRef(PyDateTime_TimeZone_UTC));
  5504. }
  5505. /* Attach new tzinfo and let fromutc() do the rest. */
  5506. if (tzinfo == Py_None) {
  5507. tzinfo = local_timezone(result);
  5508. if (tzinfo == NULL) {
  5509. Py_DECREF(result);
  5510. return NULL;
  5511. }
  5512. }
  5513. else
  5514. Py_INCREF(tzinfo);
  5515. Py_SETREF(result->tzinfo, tzinfo);
  5516. temp = (PyObject *)result;
  5517. result = (PyDateTime_DateTime *)
  5518. PyObject_CallMethodOneArg(tzinfo, &_Py_ID(fromutc), temp);
  5519. Py_DECREF(temp);
  5520. return result;
  5521. }
  5522. static PyObject *
  5523. datetime_timetuple(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5524. {
  5525. int dstflag = -1;
  5526. if (HASTZINFO(self) && self->tzinfo != Py_None) {
  5527. PyObject * dst;
  5528. dst = call_dst(self->tzinfo, (PyObject *)self);
  5529. if (dst == NULL)
  5530. return NULL;
  5531. if (dst != Py_None)
  5532. dstflag = delta_bool((PyDateTime_Delta *)dst);
  5533. Py_DECREF(dst);
  5534. }
  5535. return build_struct_time(GET_YEAR(self),
  5536. GET_MONTH(self),
  5537. GET_DAY(self),
  5538. DATE_GET_HOUR(self),
  5539. DATE_GET_MINUTE(self),
  5540. DATE_GET_SECOND(self),
  5541. dstflag);
  5542. }
  5543. static long long
  5544. local_to_seconds(int year, int month, int day,
  5545. int hour, int minute, int second, int fold)
  5546. {
  5547. long long t, a, b, u1, u2, t1, t2, lt;
  5548. t = utc_to_seconds(year, month, day, hour, minute, second);
  5549. /* Our goal is to solve t = local(u) for u. */
  5550. lt = local(t);
  5551. if (lt == -1)
  5552. return -1;
  5553. a = lt - t;
  5554. u1 = t - a;
  5555. t1 = local(u1);
  5556. if (t1 == -1)
  5557. return -1;
  5558. if (t1 == t) {
  5559. /* We found one solution, but it may not be the one we need.
  5560. * Look for an earlier solution (if `fold` is 0), or a
  5561. * later one (if `fold` is 1). */
  5562. if (fold)
  5563. u2 = u1 + max_fold_seconds;
  5564. else
  5565. u2 = u1 - max_fold_seconds;
  5566. lt = local(u2);
  5567. if (lt == -1)
  5568. return -1;
  5569. b = lt - u2;
  5570. if (a == b)
  5571. return u1;
  5572. }
  5573. else {
  5574. b = t1 - u1;
  5575. assert(a != b);
  5576. }
  5577. u2 = t - b;
  5578. t2 = local(u2);
  5579. if (t2 == -1)
  5580. return -1;
  5581. if (t2 == t)
  5582. return u2;
  5583. if (t1 == t)
  5584. return u1;
  5585. /* We have found both offsets a and b, but neither t - a nor t - b is
  5586. * a solution. This means t is in the gap. */
  5587. return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
  5588. }
  5589. /* date(1970,1,1).toordinal() == 719163 */
  5590. #define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
  5591. static PyObject *
  5592. datetime_timestamp(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5593. {
  5594. PyObject *result;
  5595. if (HASTZINFO(self) && self->tzinfo != Py_None) {
  5596. PyObject *delta;
  5597. delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
  5598. if (delta == NULL)
  5599. return NULL;
  5600. result = delta_total_seconds(delta, NULL);
  5601. Py_DECREF(delta);
  5602. }
  5603. else {
  5604. long long seconds;
  5605. seconds = local_to_seconds(GET_YEAR(self),
  5606. GET_MONTH(self),
  5607. GET_DAY(self),
  5608. DATE_GET_HOUR(self),
  5609. DATE_GET_MINUTE(self),
  5610. DATE_GET_SECOND(self),
  5611. DATE_GET_FOLD(self));
  5612. if (seconds == -1)
  5613. return NULL;
  5614. result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
  5615. DATE_GET_MICROSECOND(self) / 1e6);
  5616. }
  5617. return result;
  5618. }
  5619. static PyObject *
  5620. datetime_getdate(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5621. {
  5622. return new_date(GET_YEAR(self),
  5623. GET_MONTH(self),
  5624. GET_DAY(self));
  5625. }
  5626. static PyObject *
  5627. datetime_gettime(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5628. {
  5629. return new_time(DATE_GET_HOUR(self),
  5630. DATE_GET_MINUTE(self),
  5631. DATE_GET_SECOND(self),
  5632. DATE_GET_MICROSECOND(self),
  5633. Py_None,
  5634. DATE_GET_FOLD(self));
  5635. }
  5636. static PyObject *
  5637. datetime_gettimetz(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5638. {
  5639. return new_time(DATE_GET_HOUR(self),
  5640. DATE_GET_MINUTE(self),
  5641. DATE_GET_SECOND(self),
  5642. DATE_GET_MICROSECOND(self),
  5643. GET_DT_TZINFO(self),
  5644. DATE_GET_FOLD(self));
  5645. }
  5646. static PyObject *
  5647. datetime_utctimetuple(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
  5648. {
  5649. int y, m, d, hh, mm, ss;
  5650. PyObject *tzinfo;
  5651. PyDateTime_DateTime *utcself;
  5652. tzinfo = GET_DT_TZINFO(self);
  5653. if (tzinfo == Py_None) {
  5654. utcself = (PyDateTime_DateTime*)Py_NewRef(self);
  5655. }
  5656. else {
  5657. PyObject *offset;
  5658. offset = call_utcoffset(tzinfo, (PyObject *)self);
  5659. if (offset == NULL)
  5660. return NULL;
  5661. if (offset == Py_None) {
  5662. Py_DECREF(offset);
  5663. utcself = (PyDateTime_DateTime*)Py_NewRef(self);
  5664. }
  5665. else {
  5666. utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
  5667. (PyDateTime_Delta *)offset, -1);
  5668. Py_DECREF(offset);
  5669. if (utcself == NULL)
  5670. return NULL;
  5671. }
  5672. }
  5673. y = GET_YEAR(utcself);
  5674. m = GET_MONTH(utcself);
  5675. d = GET_DAY(utcself);
  5676. hh = DATE_GET_HOUR(utcself);
  5677. mm = DATE_GET_MINUTE(utcself);
  5678. ss = DATE_GET_SECOND(utcself);
  5679. Py_DECREF(utcself);
  5680. return build_struct_time(y, m, d, hh, mm, ss, 0);
  5681. }
  5682. /* Pickle support, a simple use of __reduce__. */
  5683. /* Let basestate be the non-tzinfo data string.
  5684. * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
  5685. * So it's a tuple in any (non-error) case.
  5686. * __getstate__ isn't exposed.
  5687. */
  5688. static PyObject *
  5689. datetime_getstate(PyDateTime_DateTime *self, int proto)
  5690. {
  5691. PyObject *basestate;
  5692. PyObject *result = NULL;
  5693. basestate = PyBytes_FromStringAndSize((char *)self->data,
  5694. _PyDateTime_DATETIME_DATASIZE);
  5695. if (basestate != NULL) {
  5696. if (proto > 3 && DATE_GET_FOLD(self))
  5697. /* Set the first bit of the third byte */
  5698. PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
  5699. if (! HASTZINFO(self) || self->tzinfo == Py_None)
  5700. result = PyTuple_Pack(1, basestate);
  5701. else
  5702. result = PyTuple_Pack(2, basestate, self->tzinfo);
  5703. Py_DECREF(basestate);
  5704. }
  5705. return result;
  5706. }
  5707. static PyObject *
  5708. datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
  5709. {
  5710. int proto;
  5711. if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
  5712. return NULL;
  5713. return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
  5714. }
  5715. static PyObject *
  5716. datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
  5717. {
  5718. return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
  5719. }
  5720. static PyMethodDef datetime_methods[] = {
  5721. /* Class methods: */
  5722. DATETIME_DATETIME_NOW_METHODDEF
  5723. {"utcnow", (PyCFunction)datetime_utcnow,
  5724. METH_NOARGS | METH_CLASS,
  5725. PyDoc_STR("Return a new datetime representing UTC day and time.")},
  5726. {"fromtimestamp", _PyCFunction_CAST(datetime_fromtimestamp),
  5727. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  5728. PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
  5729. {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
  5730. METH_VARARGS | METH_CLASS,
  5731. PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
  5732. {"strptime", (PyCFunction)datetime_strptime,
  5733. METH_VARARGS | METH_CLASS,
  5734. PyDoc_STR("string, format -> new datetime parsed from a string "
  5735. "(like time.strptime()).")},
  5736. {"combine", _PyCFunction_CAST(datetime_combine),
  5737. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  5738. PyDoc_STR("date, time -> datetime with same date and time fields")},
  5739. {"fromisoformat", (PyCFunction)datetime_fromisoformat,
  5740. METH_O | METH_CLASS,
  5741. PyDoc_STR("string -> datetime from a string in most ISO 8601 formats")},
  5742. /* Instance methods: */
  5743. {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
  5744. PyDoc_STR("Return date object with same year, month and day.")},
  5745. {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
  5746. PyDoc_STR("Return time object with same time but with tzinfo=None.")},
  5747. {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
  5748. PyDoc_STR("Return time object with same time and tzinfo.")},
  5749. {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
  5750. PyDoc_STR("Return ctime() style string.")},
  5751. {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
  5752. PyDoc_STR("Return time tuple, compatible with time.localtime().")},
  5753. {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
  5754. PyDoc_STR("Return POSIX timestamp as float.")},
  5755. {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
  5756. PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
  5757. {"isoformat", _PyCFunction_CAST(datetime_isoformat), METH_VARARGS | METH_KEYWORDS,
  5758. PyDoc_STR("[sep] -> string in ISO 8601 format, "
  5759. "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
  5760. "sep is used to separate the year from the time, and "
  5761. "defaults to 'T'.\n"
  5762. "The optional argument timespec specifies the number "
  5763. "of additional terms\nof the time to include. Valid "
  5764. "options are 'auto', 'hours', 'minutes',\n'seconds', "
  5765. "'milliseconds' and 'microseconds'.\n")},
  5766. {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
  5767. PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
  5768. {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
  5769. PyDoc_STR("Return self.tzinfo.tzname(self).")},
  5770. {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
  5771. PyDoc_STR("Return self.tzinfo.dst(self).")},
  5772. {"replace", _PyCFunction_CAST(datetime_replace), METH_VARARGS | METH_KEYWORDS,
  5773. PyDoc_STR("Return datetime with new specified fields.")},
  5774. {"astimezone", _PyCFunction_CAST(datetime_astimezone), METH_VARARGS | METH_KEYWORDS,
  5775. PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
  5776. {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
  5777. PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
  5778. {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
  5779. PyDoc_STR("__reduce__() -> (cls, state)")},
  5780. {NULL, NULL}
  5781. };
  5782. static const char datetime_doc[] =
  5783. PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
  5784. \n\
  5785. The year, month and day arguments are required. tzinfo may be None, or an\n\
  5786. instance of a tzinfo subclass. The remaining arguments may be ints.\n");
  5787. static PyNumberMethods datetime_as_number = {
  5788. datetime_add, /* nb_add */
  5789. datetime_subtract, /* nb_subtract */
  5790. 0, /* nb_multiply */
  5791. 0, /* nb_remainder */
  5792. 0, /* nb_divmod */
  5793. 0, /* nb_power */
  5794. 0, /* nb_negative */
  5795. 0, /* nb_positive */
  5796. 0, /* nb_absolute */
  5797. 0, /* nb_bool */
  5798. };
  5799. static PyTypeObject PyDateTime_DateTimeType = {
  5800. PyVarObject_HEAD_INIT(NULL, 0)
  5801. "datetime.datetime", /* tp_name */
  5802. sizeof(PyDateTime_DateTime), /* tp_basicsize */
  5803. 0, /* tp_itemsize */
  5804. (destructor)datetime_dealloc, /* tp_dealloc */
  5805. 0, /* tp_vectorcall_offset */
  5806. 0, /* tp_getattr */
  5807. 0, /* tp_setattr */
  5808. 0, /* tp_as_async */
  5809. (reprfunc)datetime_repr, /* tp_repr */
  5810. &datetime_as_number, /* tp_as_number */
  5811. 0, /* tp_as_sequence */
  5812. 0, /* tp_as_mapping */
  5813. (hashfunc)datetime_hash, /* tp_hash */
  5814. 0, /* tp_call */
  5815. (reprfunc)datetime_str, /* tp_str */
  5816. PyObject_GenericGetAttr, /* tp_getattro */
  5817. 0, /* tp_setattro */
  5818. 0, /* tp_as_buffer */
  5819. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  5820. datetime_doc, /* tp_doc */
  5821. 0, /* tp_traverse */
  5822. 0, /* tp_clear */
  5823. datetime_richcompare, /* tp_richcompare */
  5824. 0, /* tp_weaklistoffset */
  5825. 0, /* tp_iter */
  5826. 0, /* tp_iternext */
  5827. datetime_methods, /* tp_methods */
  5828. 0, /* tp_members */
  5829. datetime_getset, /* tp_getset */
  5830. 0, /* tp_base; filled in
  5831. PyInit__datetime */
  5832. 0, /* tp_dict */
  5833. 0, /* tp_descr_get */
  5834. 0, /* tp_descr_set */
  5835. 0, /* tp_dictoffset */
  5836. 0, /* tp_init */
  5837. datetime_alloc, /* tp_alloc */
  5838. datetime_new, /* tp_new */
  5839. 0, /* tp_free */
  5840. };
  5841. /* ---------------------------------------------------------------------------
  5842. * Module methods and initialization.
  5843. */
  5844. static PyMethodDef module_methods[] = {
  5845. {NULL, NULL}
  5846. };
  5847. /* Get a new C API by calling this function.
  5848. * Clients get at C API via PyDateTime_IMPORT, defined in datetime.h.
  5849. */
  5850. static inline PyDateTime_CAPI *
  5851. get_datetime_capi(void)
  5852. {
  5853. PyDateTime_CAPI *capi = PyMem_Malloc(sizeof(PyDateTime_CAPI));
  5854. if (capi == NULL) {
  5855. PyErr_NoMemory();
  5856. return NULL;
  5857. }
  5858. capi->DateType = &PyDateTime_DateType;
  5859. capi->DateTimeType = &PyDateTime_DateTimeType;
  5860. capi->TimeType = &PyDateTime_TimeType;
  5861. capi->DeltaType = &PyDateTime_DeltaType;
  5862. capi->TZInfoType = &PyDateTime_TZInfoType;
  5863. capi->Date_FromDate = new_date_ex;
  5864. capi->DateTime_FromDateAndTime = new_datetime_ex;
  5865. capi->Time_FromTime = new_time_ex;
  5866. capi->Delta_FromDelta = new_delta_ex;
  5867. capi->TimeZone_FromTimeZone = new_timezone;
  5868. capi->DateTime_FromTimestamp = datetime_fromtimestamp;
  5869. capi->Date_FromTimestamp = datetime_date_fromtimestamp_capi;
  5870. capi->DateTime_FromDateAndTimeAndFold = new_datetime_ex2;
  5871. capi->Time_FromTimeAndFold = new_time_ex2;
  5872. // Make sure this function is called after PyDateTime_TimeZone_UTC has
  5873. // been initialized.
  5874. assert(PyDateTime_TimeZone_UTC != NULL);
  5875. capi->TimeZone_UTC = PyDateTime_TimeZone_UTC; // borrowed ref
  5876. return capi;
  5877. }
  5878. static void
  5879. datetime_destructor(PyObject *op)
  5880. {
  5881. void *ptr = PyCapsule_GetPointer(op, PyDateTime_CAPSULE_NAME);
  5882. PyMem_Free(ptr);
  5883. }
  5884. static int
  5885. _datetime_exec(PyObject *module)
  5886. {
  5887. // `&...` is not a constant expression according to a strict reading
  5888. // of C standards. Fill tp_base at run-time rather than statically.
  5889. // See https://bugs.python.org/issue40777
  5890. PyDateTime_IsoCalendarDateType.tp_base = &PyTuple_Type;
  5891. PyDateTime_TimeZoneType.tp_base = &PyDateTime_TZInfoType;
  5892. PyDateTime_DateTimeType.tp_base = &PyDateTime_DateType;
  5893. PyTypeObject *types[] = {
  5894. &PyDateTime_DateType,
  5895. &PyDateTime_DateTimeType,
  5896. &PyDateTime_TimeType,
  5897. &PyDateTime_DeltaType,
  5898. &PyDateTime_TZInfoType,
  5899. &PyDateTime_TimeZoneType,
  5900. };
  5901. for (size_t i = 0; i < Py_ARRAY_LENGTH(types); i++) {
  5902. if (PyModule_AddType(module, types[i]) < 0) {
  5903. return -1;
  5904. }
  5905. }
  5906. if (PyType_Ready(&PyDateTime_IsoCalendarDateType) < 0) {
  5907. return -1;
  5908. }
  5909. #define DATETIME_ADD_MACRO(dict, c, value_expr) \
  5910. do { \
  5911. PyObject *value = (value_expr); \
  5912. if (value == NULL) { \
  5913. return -1; \
  5914. } \
  5915. if (PyDict_SetItemString(dict, c, value) < 0) { \
  5916. Py_DECREF(value); \
  5917. return -1; \
  5918. } \
  5919. Py_DECREF(value); \
  5920. } while(0)
  5921. /* timedelta values */
  5922. PyObject *d = PyDateTime_DeltaType.tp_dict;
  5923. DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
  5924. DATETIME_ADD_MACRO(d, "min", new_delta(-MAX_DELTA_DAYS, 0, 0, 0));
  5925. DATETIME_ADD_MACRO(d, "max",
  5926. new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0));
  5927. /* date values */
  5928. d = PyDateTime_DateType.tp_dict;
  5929. DATETIME_ADD_MACRO(d, "min", new_date(1, 1, 1));
  5930. DATETIME_ADD_MACRO(d, "max", new_date(MAXYEAR, 12, 31));
  5931. DATETIME_ADD_MACRO(d, "resolution", new_delta(1, 0, 0, 0));
  5932. /* time values */
  5933. d = PyDateTime_TimeType.tp_dict;
  5934. DATETIME_ADD_MACRO(d, "min", new_time(0, 0, 0, 0, Py_None, 0));
  5935. DATETIME_ADD_MACRO(d, "max", new_time(23, 59, 59, 999999, Py_None, 0));
  5936. DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
  5937. /* datetime values */
  5938. d = PyDateTime_DateTimeType.tp_dict;
  5939. DATETIME_ADD_MACRO(d, "min",
  5940. new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0));
  5941. DATETIME_ADD_MACRO(d, "max", new_datetime(MAXYEAR, 12, 31, 23, 59, 59,
  5942. 999999, Py_None, 0));
  5943. DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
  5944. /* timezone values */
  5945. d = PyDateTime_TimeZoneType.tp_dict;
  5946. PyObject *delta = new_delta(0, 0, 0, 0);
  5947. if (delta == NULL) {
  5948. return -1;
  5949. }
  5950. PyObject *x = create_timezone(delta, NULL);
  5951. Py_DECREF(delta);
  5952. if (x == NULL) {
  5953. return -1;
  5954. }
  5955. if (PyDict_SetItemString(d, "utc", x) < 0) {
  5956. Py_DECREF(x);
  5957. return -1;
  5958. }
  5959. PyDateTime_TimeZone_UTC = x;
  5960. /* bpo-37642: These attributes are rounded to the nearest minute for backwards
  5961. * compatibility, even though the constructor will accept a wider range of
  5962. * values. This may change in the future.*/
  5963. delta = new_delta(-1, 60, 0, 1); /* -23:59 */
  5964. if (delta == NULL) {
  5965. return -1;
  5966. }
  5967. x = create_timezone(delta, NULL);
  5968. Py_DECREF(delta);
  5969. DATETIME_ADD_MACRO(d, "min", x);
  5970. delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
  5971. if (delta == NULL) {
  5972. return -1;
  5973. }
  5974. x = create_timezone(delta, NULL);
  5975. Py_DECREF(delta);
  5976. DATETIME_ADD_MACRO(d, "max", x);
  5977. /* Epoch */
  5978. PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
  5979. PyDateTime_TimeZone_UTC, 0);
  5980. if (PyDateTime_Epoch == NULL) {
  5981. return -1;
  5982. }
  5983. /* module initialization */
  5984. if (PyModule_AddIntMacro(module, MINYEAR) < 0) {
  5985. return -1;
  5986. }
  5987. if (PyModule_AddIntMacro(module, MAXYEAR) < 0) {
  5988. return -1;
  5989. }
  5990. PyDateTime_CAPI *capi = get_datetime_capi();
  5991. if (capi == NULL) {
  5992. return -1;
  5993. }
  5994. x = PyCapsule_New(capi, PyDateTime_CAPSULE_NAME, datetime_destructor);
  5995. if (x == NULL) {
  5996. PyMem_Free(capi);
  5997. return -1;
  5998. }
  5999. if (PyModule_AddObject(module, "datetime_CAPI", x) < 0) {
  6000. Py_DECREF(x);
  6001. return -1;
  6002. }
  6003. if (PyModule_AddObjectRef(module, "UTC", PyDateTime_TimeZone_UTC) < 0) {
  6004. return -1;
  6005. }
  6006. /* A 4-year cycle has an extra leap day over what we'd get from
  6007. * pasting together 4 single years.
  6008. */
  6009. static_assert(DI4Y == 4 * 365 + 1, "DI4Y");
  6010. assert(DI4Y == days_before_year(4+1));
  6011. /* Similarly, a 400-year cycle has an extra leap day over what we'd
  6012. * get from pasting together 4 100-year cycles.
  6013. */
  6014. static_assert(DI400Y == 4 * DI100Y + 1, "DI400Y");
  6015. assert(DI400Y == days_before_year(400+1));
  6016. /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
  6017. * pasting together 25 4-year cycles.
  6018. */
  6019. static_assert(DI100Y == 25 * DI4Y - 1, "DI100Y");
  6020. assert(DI100Y == days_before_year(100+1));
  6021. us_per_ms = PyLong_FromLong(1000);
  6022. if (us_per_ms == NULL) {
  6023. goto error;
  6024. }
  6025. us_per_second = PyLong_FromLong(1000000);
  6026. if (us_per_second == NULL) {
  6027. goto error;
  6028. }
  6029. us_per_minute = PyLong_FromLong(60000000);
  6030. if (us_per_minute == NULL) {
  6031. goto error;
  6032. }
  6033. seconds_per_day = PyLong_FromLong(24 * 3600);
  6034. if (seconds_per_day == NULL) {
  6035. goto error;
  6036. }
  6037. /* The rest are too big for 32-bit ints, but even
  6038. * us_per_week fits in 40 bits, so doubles should be exact.
  6039. */
  6040. us_per_hour = PyLong_FromDouble(3600000000.0);
  6041. if (us_per_hour == NULL) {
  6042. goto error;
  6043. }
  6044. us_per_day = PyLong_FromDouble(86400000000.0);
  6045. if (us_per_day == NULL) {
  6046. goto error;
  6047. }
  6048. us_per_week = PyLong_FromDouble(604800000000.0);
  6049. if (us_per_week == NULL) {
  6050. goto error;
  6051. }
  6052. return 0;
  6053. error:
  6054. Py_XDECREF(us_per_ms);
  6055. Py_XDECREF(us_per_second);
  6056. Py_XDECREF(us_per_minute);
  6057. Py_XDECREF(us_per_hour);
  6058. Py_XDECREF(us_per_day);
  6059. Py_XDECREF(us_per_week);
  6060. Py_XDECREF(seconds_per_day);
  6061. return -1;
  6062. }
  6063. static struct PyModuleDef datetimemodule = {
  6064. PyModuleDef_HEAD_INIT,
  6065. .m_name = "_datetime",
  6066. .m_doc = "Fast implementation of the datetime type.",
  6067. .m_size = -1,
  6068. .m_methods = module_methods,
  6069. };
  6070. PyMODINIT_FUNC
  6071. PyInit__datetime(void)
  6072. {
  6073. PyObject *mod = PyModule_Create(&datetimemodule);
  6074. if (mod == NULL)
  6075. return NULL;
  6076. if (_datetime_exec(mod) < 0) {
  6077. Py_DECREF(mod);
  6078. return NULL;
  6079. }
  6080. return mod;
  6081. }
  6082. /* ---------------------------------------------------------------------------
  6083. Some time zone algebra. For a datetime x, let
  6084. x.n = x stripped of its timezone -- its naive time.
  6085. x.o = x.utcoffset(), and assuming that doesn't raise an exception or
  6086. return None
  6087. x.d = x.dst(), and assuming that doesn't raise an exception or
  6088. return None
  6089. x.s = x's standard offset, x.o - x.d
  6090. Now some derived rules, where k is a duration (timedelta).
  6091. 1. x.o = x.s + x.d
  6092. This follows from the definition of x.s.
  6093. 2. If x and y have the same tzinfo member, x.s = y.s.
  6094. This is actually a requirement, an assumption we need to make about
  6095. sane tzinfo classes.
  6096. 3. The naive UTC time corresponding to x is x.n - x.o.
  6097. This is again a requirement for a sane tzinfo class.
  6098. 4. (x+k).s = x.s
  6099. This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
  6100. 5. (x+k).n = x.n + k
  6101. Again follows from how arithmetic is defined.
  6102. Now we can explain tz.fromutc(x). Let's assume it's an interesting case
  6103. (meaning that the various tzinfo methods exist, and don't blow up or return
  6104. None when called).
  6105. The function wants to return a datetime y with timezone tz, equivalent to x.
  6106. x is already in UTC.
  6107. By #3, we want
  6108. y.n - y.o = x.n [1]
  6109. The algorithm starts by attaching tz to x.n, and calling that y. So
  6110. x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
  6111. becomes true; in effect, we want to solve [2] for k:
  6112. (y+k).n - (y+k).o = x.n [2]
  6113. By #1, this is the same as
  6114. (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
  6115. By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
  6116. Substituting that into [3],
  6117. x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
  6118. k - (y+k).s - (y+k).d = 0; rearranging,
  6119. k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
  6120. k = y.s - (y+k).d
  6121. On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
  6122. approximate k by ignoring the (y+k).d term at first. Note that k can't be
  6123. very large, since all offset-returning methods return a duration of magnitude
  6124. less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
  6125. be 0, so ignoring it has no consequence then.
  6126. In any case, the new value is
  6127. z = y + y.s [4]
  6128. It's helpful to step back at look at [4] from a higher level: it's simply
  6129. mapping from UTC to tz's standard time.
  6130. At this point, if
  6131. z.n - z.o = x.n [5]
  6132. we have an equivalent time, and are almost done. The insecurity here is
  6133. at the start of daylight time. Picture US Eastern for concreteness. The wall
  6134. time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
  6135. sense then. The docs ask that an Eastern tzinfo class consider such a time to
  6136. be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
  6137. on the day DST starts. We want to return the 1:MM EST spelling because that's
  6138. the only spelling that makes sense on the local wall clock.
  6139. In fact, if [5] holds at this point, we do have the standard-time spelling,
  6140. but that takes a bit of proof. We first prove a stronger result. What's the
  6141. difference between the LHS and RHS of [5]? Let
  6142. diff = x.n - (z.n - z.o) [6]
  6143. Now
  6144. z.n = by [4]
  6145. (y + y.s).n = by #5
  6146. y.n + y.s = since y.n = x.n
  6147. x.n + y.s = since z and y are have the same tzinfo member,
  6148. y.s = z.s by #2
  6149. x.n + z.s
  6150. Plugging that back into [6] gives
  6151. diff =
  6152. x.n - ((x.n + z.s) - z.o) = expanding
  6153. x.n - x.n - z.s + z.o = cancelling
  6154. - z.s + z.o = by #2
  6155. z.d
  6156. So diff = z.d.
  6157. If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
  6158. spelling we wanted in the endcase described above. We're done. Contrarily,
  6159. if z.d = 0, then we have a UTC equivalent, and are also done.
  6160. If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
  6161. add to z (in effect, z is in tz's standard time, and we need to shift the
  6162. local clock into tz's daylight time).
  6163. Let
  6164. z' = z + z.d = z + diff [7]
  6165. and we can again ask whether
  6166. z'.n - z'.o = x.n [8]
  6167. If so, we're done. If not, the tzinfo class is insane, according to the
  6168. assumptions we've made. This also requires a bit of proof. As before, let's
  6169. compute the difference between the LHS and RHS of [8] (and skipping some of
  6170. the justifications for the kinds of substitutions we've done several times
  6171. already):
  6172. diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
  6173. x.n - (z.n + diff - z'.o) = replacing diff via [6]
  6174. x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
  6175. x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
  6176. - z.n + z.n - z.o + z'.o = cancel z.n
  6177. - z.o + z'.o = #1 twice
  6178. -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
  6179. z'.d - z.d
  6180. So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
  6181. we've found the UTC-equivalent so are done. In fact, we stop with [7] and
  6182. return z', not bothering to compute z'.d.
  6183. How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
  6184. a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
  6185. would have to change the result dst() returns: we start in DST, and moving
  6186. a little further into it takes us out of DST.
  6187. There isn't a sane case where this can happen. The closest it gets is at
  6188. the end of DST, where there's an hour in UTC with no spelling in a hybrid
  6189. tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
  6190. that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
  6191. UTC) because the docs insist on that, but 0:MM is taken as being in daylight
  6192. time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
  6193. clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
  6194. standard time. Since that's what the local clock *does*, we want to map both
  6195. UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
  6196. in local time, but so it goes -- it's the way the local clock works.
  6197. When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
  6198. so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
  6199. z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
  6200. (correctly) concludes that z' is not UTC-equivalent to x.
  6201. Because we know z.d said z was in daylight time (else [5] would have held and
  6202. we would have stopped then), and we know z.d != z'.d (else [8] would have held
  6203. and we would have stopped then), and there are only 2 possible values dst() can
  6204. return in Eastern, it follows that z'.d must be 0 (which it is in the example,
  6205. but the reasoning doesn't depend on the example -- it depends on there being
  6206. two possible dst() outcomes, one zero and the other non-zero). Therefore
  6207. z' must be in standard time, and is the spelling we want in this case.
  6208. Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
  6209. concerned (because it takes z' as being in standard time rather than the
  6210. daylight time we intend here), but returning it gives the real-life "local
  6211. clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
  6212. tz.
  6213. When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
  6214. the 1:MM standard time spelling we want.
  6215. So how can this break? One of the assumptions must be violated. Two
  6216. possibilities:
  6217. 1) [2] effectively says that y.s is invariant across all y belong to a given
  6218. time zone. This isn't true if, for political reasons or continental drift,
  6219. a region decides to change its base offset from UTC.
  6220. 2) There may be versions of "double daylight" time where the tail end of
  6221. the analysis gives up a step too early. I haven't thought about that
  6222. enough to say.
  6223. In any case, it's clear that the default fromutc() is strong enough to handle
  6224. "almost all" time zones: so long as the standard offset is invariant, it
  6225. doesn't matter if daylight time transition points change from year to year, or
  6226. if daylight time is skipped in some years; it doesn't matter how large or
  6227. small dst() may get within its bounds; and it doesn't even matter if some
  6228. perverse time zone returns a negative dst()). So a breaking case must be
  6229. pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
  6230. --------------------------------------------------------------------------- */