Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
80 views

Advanced Python Programming - Lesson No.004

Advanced Python Programming - Lesson No.004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
80 views

Advanced Python Programming - Lesson No.004

Advanced Python Programming - Lesson No.004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 23
Date and time in python : Date and time now, combining date and time, formatting dates and times, finding durations using “time delta’, comparing two dates, sorting dates, stopping execution temporarily, knowing the time taken by program, calendar module. W_ Advanced Python Programming (MU_BSC.Comp) 2 eae ——————eEE————eeeoeoOooOoooqeEe™@3e>«>ww wan a es and Thea 4110421 44 Introduction. 4.11 Date and Time Now. menennen 42 Combining Date and Time, nner 4A 43 Formatting Dates and Te eee 45 44 Finding Durations using "time delta” wnewnnnnennnnnnnnnnem “7 45 Comparing Two Dates. ennneentennnant MA 46 Sorting Dat nnn iz 4.7 Stopping Execution Temporary ennenntnnnnnnnninnnnnnnnnnnitnnn A 48 Knowing the Time Taken by a PrOgr&IMwennnnnisnnenntneneeennnnnnnsennnnenennnennennnnch 1S 49 Calendar Module. a eee ee — DATE AND TIME IN PYTHON Date and tme in python: Date and tie now, combining date and time, formating dates and times, fing urns using “ime deta, comparing to dates sertng dates. stopping execution temporarily, knowing the time taken bya program, calendar module an methods for working with Date or Time, However, ving tothe DateTime ‘ole which comes pre-installed with Pythons bas tity modules, we an easy change dat ad ime to ‘urthing. Wemay also do things ke reteve the current date a or subtract dat andtine, nd much more ‘+ Python's DateTime module is used to conduct Date and Tine operation So before we beg. lets g through ‘the fundamentals ofthe DateTime module and the ses itncudes. ‘+The datetime asses are ave int sicatgortes. 1© ate ~ An ieaised nave date presuming that the present Gregorian calendar has always been and will always ein efec. thas thre atbuts: year, month and dy. | © time Andesite that independent f any spec dy presuming tht ech ay contains precisely | 2460" seconds thas the following properties: hour, minut, second eroecond, and tifa © datetime «11s 2 date and time combination containing the qualties year, mont, day, hour, mou, second, mlrosecond and txno (© tmedelt A duration that exreses the ilerence between two dts, neo datetime occurences to the nearest mirosecond {ano This command returns tine ron nermation obec, timezone - clas that implements the abstract hase class ano aed fet from UTC | 42.1 Date and Time Now ‘The dtetimenow() method ie used to et both the current ate and Time, tine Syntax: daetinenow() earns he oa caren at and Bs 18 sever on Progra BSE omg 2 utes teeny ‘ample 2 eeenermeey ng Ce BODAptesechbapmbiensmeetendine — 2 te deacnstrase getting curtent date and tine wei ng datetine nodule for nol) | daterine cureene tine © eatetiae.datetine ec) 4 ‘The now() method provides several properties that can provide the needed deta rom the above ou Ye, month rinute and second ae among the properties. Fr a better understanding conse te felon 1 veing now() to get curcent tine Eine = davetine.datetine.no¥() peine (rine seteiboree of new) are 2" prime (vear s “ands Print (euteent_eine- year) lbeine (races sy and = 2) [print (cuerene_timesmonth) print (roay : *, end = Deine (current tame-cay! ie sy ont = (current_tine howe) (rrccote sty and 2 Ccuzeent_tine minute) Urictosecont +s ond = (cusrent_tine.nictorecone) ramming 5c fs (a Prona77 Sper — fe fet Set tug Optom Window He he attrinue Year’: 2022 of now) are: Month : 2) Day: 1 Hour: 14 Minute : 43 Second : 12 Microsecona + 542332 ‘The DateTime module alsoincldes a metho names da tht merely outputs the vale of the cure dt, | (a redeyey Cruse teNovorAgpOaetocalPregamihy. —— OX Fae fat Format Ron Optens Window Help # Python program to get current date from datetime inport date today = date. today() print ("Today da: ", today) Teme Wie can createa time objec using the time function Consde the Below example. Dtineny-civeantenovo/appDaanccalProg.. — OX Fle tt Format Ran Options Window Help From datetine import datetime ‘time = datetime-now () -time () print ("current Tims =", time) (2 Pyten 3775p —o x Advanced tan Progr 4.2 Combining Date and Time We may make a'dattine ass obec by merging date and tne c ‘Please hee In mind tat the date and time lasses are par ofthe ‘atsime’ module, Fr example we may ba date clase abet using he falling date = date (2022 1,2) Simian we can build time clas abject and save some tine a follows Aaetne. ime = £ (10,30) St object with the combine() unt ‘The combine) fonction snow cass method Inthe dattin’ clas that may combine the previously produ tects as ols ‘areimecombine = datetinecombine (1) output: Ta “combine eo tne py -C/sen/NOVOFApp. Fle Edt Format Ran = datetine import * date(2022, 1, 1) t= time(i0, 30) dt = datetine.combine(d, t) print (dt) (a Pon ar7 Se =o x | Fle_tet Stall Debug Opens Window Hep 2022-01-02 10:30:00 a CE ae ‘Toe combine) functions used to creat adatetie’obectin the second way atetimecombine = dt (41) ‘The third method of generating ‘tetime’ oject sto create the object rectly and supply the dae and tine aes ae Dateimeyear=2022, months, days) = 3 (4 date and ime (202, 1,1,11,30) Datetime(year=2022, mone ayet, hour, minute=30) ‘Wemay update the content of the'datetie’ objec by using the replace function as follows 6 = ds replace(2021, monthe12) ee urput: 2022-01-01 11:30:10 sepystcos Zos30.0 43__Formatting Dates and Times Dierent date formats are used in diferen parts of the word To deal with uch formating DateTime provides ‘he srftime() function This method converts date and time objects to string representations. aceps one or more ine formated code as Input and returns the sting representation. now = datetime.now() # current date and time = now. ate teine rinecyear's year) Inonth = now.atsfe ime" prime Gwar ss month day = now.eerteine ("9s") Jpelne "Say", aay) eine = now. stzfeime (85 §985°) proneerine'"y. Eime) prince” Tice tine) ivan “6 Output Fe E3t Shel Oetup Opns Wnfow a year: 2023 month: 02 day: 02 Sime: 15:24:44 age ant le: oayxrsons, as:2ese “The Table 4. gives reference ofall the legal format codes: ond Tin Table 43 Directive Meaning Example ‘ha | Abbreviated weekday name sun, Mon 6A | Pu weekday mame, Sunday, Monday, ‘hoe | Weeksay asa decimal number O16 sd _ | pay ofthe month a zro-paded decimal 01,02,431 ed _| Day ofthe month asa decimal number. 1.20130 ib__| Abbrevited month ame fan Feb, — Dee. 66 | Fulmonth name. fanuary. February. sm _| Month asa zro-paded decimal umber 01, 02,112 sem | Monthasa decimal number. 12et2 ‘hy _| Year without century as. zero-padded decimal number. 00,01, 99 sey _| Year without century a delmal number 0.1.99 s6y | Yearwith century aba decimal number 2013,2019 ee. suit _| Hour (24-hour clock asa zero-paed decimal number 00,01, -.23 wet | Hour(2¢our dock asa decimal number. 0,1.-.23 sot | Hour (12-hour clock asa zero-paded decimal number. 01.02.0012 viet [Hour (12-tour clock) asa decimal number 12212 _j aos—w(vj]—“——1'" Progra 85 Cong Directive Meaning | | tocaesamorrm, fn {44 _| Minute aca sero-paed decimal inter, 00.01.59 Pe er 58 145 _| second asa zrpaddd decal number 90,01 58 45 _| Sends decimal numer 1,58 {| miorcond 2a decimal numer zropaded onthe of 200000-959088 see _[urcomiein form HMM o HH 7 2 | timezone name . 41 _| bay tthe years erga decimal umber. 001,002 -.366 161 _[ Dayotteyearara decal number 12.366 sw | Weoknumberorte year (Sunday atheist day ofthe week at | 00,01..58 daysina new year receding the st Sunday are considered to ben sew | Weck number ote year Monday the rt dy othe wee) A {ays ina new year preceding he fie! Monday are considered to bein week 16 _| Locate approprise dite andi ‘Mon Sep3007.0605 2013, sex _ | Loae'saproprte dt reresetaton onps0/s3 4x _| Laci poropriate time representation. 70605 sm _[ Attra hare, % 44 _ Finding Durations using "time delta” +The uetne library ices the Python ined ton. To compute the dference between two dates. we tlie he Python ined anton. You may alo we Python ined to sntipatepstand fate dates. + inhi par. we present the grtetsumber of ietances of hs Python cimedels This Python datetine ‘sede method bas the flowing syntax: Stan atte inedetadaye = 0 seconde =O. microsecond =, mllesconds = 0, minutes “0, huts #0. weeks «) thon Pageaneing MURS Cony “ ‘The simple example of inedeta functions ven afalows o | datetine 2 erences "y daverine,cimdeicatntcroreconds 7 3)? |ben eit“) Satetine eimedeiea taitiieeconds * 2) output: ‘The datetime teeta object provides three unique properties that yield the mat egative, most postive ant smallest ference between o non-equal edt objects min, max and resolution Print ("wansmm ~ “, datetime. cimedelta.min) [Print (*Naximin “} datetime. timedelta..max) Prine rrescun ") datetine.timedeita.reolution) ine Go Output: Dron? =e Fie Ee Sha Dib Opens Winder Hp Minimin = -989999999 days, 0:00:00 * Naximim = 999999999 days, 23:59:58. 399998 feeguisien + 0:00:00,00001 ‘et me show you basic timedta ample that returns the dates one yar and two years in he ature We may declare that we ae projecting future dates by importing themed cas nt the datetime objec [Brereen-cmitsigteieatmyntinnttanimnat = BF sm to form hen ote We toy name tee wpe: TB rmmiiron =o x Fe fat Sut Onhop ind te care dates-py ‘| (Garrent Date and Tine : 2022-02-04 13:01:55.192263 bate and Tine After one Year 2023-02-04. 13:01:55.192269 Sysy an Fine of Pwo teary feom tow 2024-02-04 Hr0tSS.100263, ‘To obtain the prior dates, we remove days using he timed function. Days: sins removing 730 days trom the current date 30 in the ined code below Adzaned thon reaming (MU. BSC coy 0 ae and Tne Inside thetimedela method we use the weeks parameter to obtain the date before andar 2 weeks /4 weeks from now. Fest Import rnedet fom datetime, ee TB wvesey Chew O0/pb ont oP opemenDyheTnaan TD 2-2 dk Fam Re Opt Wd Hey - Gavecine datetine, cinedeita 4 cnn» anon enty | e_bofore_two_weeks = current_dt - timedelta(weeks = 2) rine (*SazeTiae before Tvs Wetks Fem stow | Sy ee (ae before_ two weeks)? Sc_after_two_weeks = current _dt + tinedeita(vesis = 2) eine ("oaterine after Two weoks from Moet ny ste (de after_two_weeke) ) print) {¢_betore_four_wooks = current_dt - timedelta weeks = 4) 8 nt ("oaverine Before Four Wsoxe from low sy ser (de pefore_ four weeks) ) at after sin weak = current de + cinedelta(vecks = 6) peine(esavetiae stax sin meses fron tom Currant Date and fine 1 2022-09-07 Tif DateTine before Two Weeks from Now : 2022-01-24 11;01:58.906478 DateTine after Two Weeks from Mow ; 2022-02-21 11101:58.906479 uterine before Tour Weeks from Now Saterine after eis Rests tesa now Th 2022-01-10 1101:50.986478 7 2022-03-21 11:01:58.886478 4 The days parameter was utilised within the Python tedeta method to return the date before and after? days fromnow. (@ ersey- Cent BirCippomnaiPepenchyoany oan O77) ar (ae feat fi Opt Wine Hip avetine isp.s! datetime, Cinedelts corrent_de = dacevine.now() Prine(voresne Sate sad Time © "y ate oureent_st)) de_betore_two days = current_dt - einedelta (days = 2) [prime (Sunts ans fine betsre Tas Saye teem Sse? "y ate(de Before ewo dave) ecuncenaned+ i atten owo_daye > comsant de cimaateatgaye 22) [peine(ccate and Tine cf TwerDays fem Now 1 ree t_after_swo_days)) fi — hf ie 1 St Donor ter de pejeetenm: Ti7unee etn ones vseausyroacame eyenon/Hyenens)/ 98 SSSA EAE Saat oe fpeinetsSascrne Sete noe Pate 5 -) axetonrsent 0) Dimeinraa eae Peete st erate nunca uscas/vecarangy¥Yeton7eyEROnS/72045:0Y 4 fee) es ibe ERG sits Esai "7 Goa Bowe al 2 Using timed to retrleve DateTime before two minutes nd afters mite. [a nee nce armpit etna =e ‘up: = [908 roses ao |e tae St yoo nde ey ; [Street Date and tine + 2022-02-07 11:0906.409237 ay Bae tnd Time Nocore vo Minaies, from wow f gugd-02-07 11:07:06. 409277 45 Comparing Two Dates a The comparion operators. >, te are ed to compare th two dates came | secompueny-CithentENOvOrAppDutoclhog. - OO x # Simple Python program to compare date: spsr* datetime # date in yyvy/mn/dd format ai = datetine.datetime (2021, 5, 3) 42 = datetine datetime (2021, 6, i) it comparing the dates will return 4 either True or False print ("di is greater than G2: ", dl > a2) print ("di is less than a2: ", di < a2) print ("di is not equal to a2 i", dl I= d2) di is less than d2 : di is not equal to d2 st 46 Dates (One ofthe most effective methods for sorting a set of ats isto keep them in list and use the sort function ‘This wl sort al ofthe availabe dates in thelist The ad function may be used to insert date cass obec into a is —_ re armed den ropanming W8Scomg)_413, Dein Sebo pminatpeaianntonsn aT? Dheninta eet [ff Mt oes on dee Hab ace oonmu/reny + 23/32/2982, Phe ssere gate gate teorem/erriy 14/03/3985 d S33 a7 ing Execution Temporal Tore are various ways to stop the execution tomporry a given below 4 Using sleep method ‘The Python time slgp() method suspends execution for the number of seconds specified. Sometines is eceray to pause the flow af the programme in order for multiple addtional exeutons to take place, oF simply because ofthe tility required In seh cae leep( can Be ute sine pera precee and fenble ‘mechanism to pause the flow of code or any length of ine. Tis faction derrbsthe Fanconi irr Yt agvanent pw sod Ti Pr ‘Syntax steetse) ‘The parameter sec is a Number of seconds for which the codes required tobe stopped Python Programing | Pais Deteage Will be printed after a wait of § seconds } — ee cote) 2. Using Event0.walt ‘The threading module provides the Event(.woit method. The Evenc wait) method wil pause any proces forte ‘numberof econde specified as an argument The following example demonstrates how Event works: Example Events wed inthe ode 0, walt) ‘The number S represent he numberof seconds the coe wil wat before proceeding to the net ne thats the function diplay, When the S second are up, the function display) i called and the message sprinted the terminal print (‘code Execution sta: set display. eine ("2y in Pecgeanming') Evens () wait (5) display’) tein ni oot — Porson a [Fe f4t_ Sh OWtop Optom vindew Hip al Code Execution started p>> Pye Feooramning Using Timer Asathe method avaiable wih Treading eth Tne, whichis obtaining te sae rion 2s hon time sep The Times operation is dermonstrated nthe allowing example ample ‘Time acepts input the form ely tne yon scons wellat tae a es oe rd ‘You mst we the star) method to get mer to work Te Tner ie ven § seconds nthe cod, 0 play ical when the 5 seconds are te oer [BD rtmerpy-CitsenstEnovorappomartecalProgamahonht. — OX File Est Format Run _Optons Window Hep u threading crport Timer print ("code Execution sta: a) sof dispiay(): print ("Python & earanming') t = Timer(5, display) Eestart() ¥ vei coro TD iena77 Ser Fie 64 Shek Debug Options Window Heb code Execution started po eviton rreveesming 48 the Time Taken by a Program “Tne is valuable. As prosrammers, we must bul programmes that are quick to execute However, n order to tise our programmes, we must ret understand how o compre the time It takes a programme to execute. ‘hs esson we wil learn to methods oclug the execution tie of programme in Python. ucand De ye cong _Azanced Fytton Progaming T Making ue ofthe time module In he time module of Python we haves function named time} that can be used to retrieve the curren ne To determine the ranning time of programme using the tine( function ofthe tne module follow te Instructions ew (© Before the firs lin ofthe programme i executed save the besnning ine ‘© Afterthelastline of the programme is executed, ave the ishing tine ‘Tae program's runing time wil be the itference between the finlshing and begining times. Lat slo tan example: TD pepe cn ca Ce BNO Fin it Format Rum Options Window Hp | Sarai # starting time stare = time.time() : ' e | # program body ends # ond time fend = time. time() # total time taken prince (#"suntine of the output: Drama 1 Set aot bee Oven wt = - 2 5 : 3 g : e34es27 t agi of ne stan ie sete 7 —— pazanced yon Progaming (MV 8 co bande yn 12 Making se of the timett module ‘The time) function ofthe time module may be sed to compute the execution time of ay Python application, ‘he time) function aes four parameters, Le'shaves look at these argUMeDs executed the dal valves pass (stu, whlch takes the code that run before he main programm ‘© sontisa declaration that we wish to run (sate, itsatimet We don't need to send anything to this parameter Hwe'ewsing timer objet, ‘© mumber which represents the numberof ime the statement wil be exec ‘Tobie comprehend his, consider he following example: sample “Drm ecan ane ivi nathan achapmpm manic wm (a fone he One spat: [B Python 3.7.7 She Fle Est Shel Debug Options Window Pac ser ey css or PeOg ean eacue TON” CAN EASMEZE—ETPY— | Executicn vine 15; /10.7545326 >I e128 Gok 49 Calendar Module Python has a calendar mode tat performs calendar related activites. The calendar module allows the rleaion to ostput calendars and fers era calendartelted operations. The Calendar module's fenton and classes make use ofa dealsd cen, the present Gregorian calendar stretched in both rections indefinitely ‘These calendars, by deft ave Monday atthe fist day ofthe week and Sunday a the Ist (the European convention}. Sera EE eee vane 9s se Example : To display calender of given month ofthe year [2 -eatenderey-CsenAINOVO/ARpOMeocN Progam. — 0 Fle E&t Format fun Optont Window Help # python program to display calendar of n month of the year calendar 4 display the calendar print (calendar-month (yy, mm)) Fr sa su a Sea see 1 eo) 10 11 12 13 14 15 16 17 18 19 20 21 22 23 25 26 27 28 29 30 ‘Example 2: Display calendar ofthe given year. [ [a sca yerpy-CinenENOVO/AppOMatoCal.. — 0 Fle E4t Format Ran Options Window Help p..) calendar print ("The calendar of year 2021 ie: 7) print (calendar.calendar(2021, 2, 1, 6)) a ie ing. on 49 tester (alender Cass ‘A Calendar objet ic erated by the calendar des. A Calendar object has a numberof metho for preparing ‘alendar data for formating, This dass doesnot perf any formating. Subclases are in charge ofthis The (aendar ass alows for caelatons based o at, moth and year fora varey of tasks The allowing methods are sable nthe Calendar cas [reaction [eseription erwesktays0) __|Thismethod Return an erator rth week ay numbers tat wl be used for one wee ermonthdates() _|Thismathod Rear an iterator othe mont (1-12) nthe year. [mermenthaye() [This method Returns anteratr ofa peed month an yer. ermonthays2() [This Method i used to get anteratorforthe month inthe year smart itermonthdstes( Days rerrned wi be tpler consisting of + day ofthe month number and 2 week d number SS Aavanced Pon Programming USC Comp) 4.20 ute and Tye Function Description | remontays30_ [Tis metho Rens an erator fo the mont nthe yar sar to Rermonthstes0 be not restricted by the datetime date range. Days returned wil be tuples consisting of year, 4] [_____] month anda day ofthe month numbers | ermomtdayt) [Tas method Returns an erator othe month nthe year sma ermonthte0 be not restricted bythe datetime dat range Days returned willbe tuples consisting oF 2a, month aday ofthe month, anda day ofthe week numbers. monthdatesclendar()This method is used togetalistf the weeks inthe month ofthe year as fll weeks month This method is used to get list of he weeks in the month ofthe yar as ull weeks, montdayscalendar | This method isusedo gels ofthe weeks inthe month ofthe year a full weeks. yeardatscalendar()_| This method is used to gets ofthe weeks in the month ofthe ear as full weeks, yeardays2calendar)_| This method i used to get the data for speed year. Entries the week ist are ules, day numbers and weekday oumbers. mumbers [us met i sed to pet the dts for specified yea fem ec “ent Calendar else ‘To create plain text calendars, se the extalendar cats The TentClendar class in Python allows yos to customise the calendar and use at needed renction | Description ormatmont | Used to get mons calendar ina malt-line tring prmonth() | Usedto printa months calendar as returned by formatmoath) formatyear()_| Used to get m-column calendar for an entire year a3 mult-ne tring pryear)__| set print the calendar for an entire yar a returned by formatmonthO, HTML Calendar class HTML calendars canbe generated using the HTMLCalendar clas. The HTMLCalendar clas in Python allows you to customise the calendar and use as needed. Function |Description formatmonth() | Usedte get month's calendar aan HTML table ormatyeart) | Usedto geyenrs calendar asan MTML table. formatyearpage() | Usedto get yea’ calendar asa complete HTML page. ee . .(.SS avmnced thon Poeamning Sc ‘Spl Tent Calendar cles {Glendar module provides the lowing anton for simple et ana eeeeere Pumetion Description sechrstweekay)| Function sts the day stare umber of wee |setesweehanO | Fstweekday()_[ Function returns the st wendy number By defal 0 (Monday) aon Function checks year mentioned in armument i ap oF nt eepdays0__[ Function returns the number ofleap days between the specie years arguments weektsy___[Funcion returns the week ay ausbe(@ ie Monday) ofthe date specified in arguments [mecthendert) _|Returnsa header containing abbreviated wechiny names. Function reerns two integers Rist. the starting day amber of wee as monday). second, rontrange) the number of daysin he month Returns a matric epresening 2 mons calendar. Each row represents a week: days ous mowthestendar ofthe month are represented by eros Fonction alo prints the month of specie year but thor sno need of “print operation to [prmonth) executes [month Function prints the month ofp war mentioned in arguments Function aso pits the calendar of specifi year bt there sno need of “print” operations) braid — [csemdar [Function spay the year with of characters no olies pr week nd calamnsepartons [Review Questions pian gate ante wh axa Explain now 9 and today 0 fnction. Wt short nts on timed ‘Explain wih example how to compare mo dates, ‘Explaa hom stop executon program tampon. Explain he tne than bya program for exciton plan calondar module win exam aoa

You might also like