Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

מדריך Python – פרק 13 – זמן ותאריך Date & Time

המרה בין פורמטים של תאריכים היא משימה שבשגרה עבור מחשבים. תוכנית בשפת Python יכולה להשתמש בתאריך ושעה בכל מיני דרכים, כמו כן ניתן להשתמש במודולים שנועדו לכך

מה זה טיק Tick

מרווחי זמן הם מספרים עשרוניים ביחידות של שניות. בשפת Python יש מודול זמן בשם time אשר מכיל פונקציות למניפולציית זמנים, ולהמרה בין סוגי זמן. הפונקציה ()time.time מחזירה את הזמן הנוכחי לפי שיטת Unix Time, שמראה לנו כמה טיקים\שניות עברו מאז יום חמישי, 1.1.1970, 12:00am:


import time;

ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)

Number of ticks since 12:00am, January 1, 1970: 1601052948.3074338

שימו לב כי בשורת הקוד הראשונה ייבאנו את המודול time, שהוא הכרחי להרצת תוכנית זו.

נורא פשוט לבצע פעולות אריתמטיות בטיקים, אך החיסרון בשיטה זו הוא שתאריכים שחלו לפני 1.1.1970 אינם קיימים, ובעיה נוספת שקיימת היא עם תאריכים בעתיד, שכן אי שם בשנת 2038 הספירה תיעצר משום שהיא תגיע למספר המקסימלי שהיא תוכל להגיע אליו אי פעם בפורמט הנוכחי. לפי השיטה בכל יום יש כ-86400 טיקים\שניות.

רשימות זמן בלתי משתנות Time Tuples

חלק גדול מפונקציות הזמן בשפת Python 3 משמשות כרשימת tuple בעלת 9 ספרות:

אינדקס יחידת זמן ערכים
0 שנה ב-4 ספרות 2016
1 חודש 1 עד 12
2 יום 1 עד 31
3 שעה 0 עד 23
4 דקה 0 עד 59
5 שניה 0 עד 60 או 61 בהתאם
6 יום בשבוע 0 עד 6, 0 זה יום שני
7 יום בשנה 1 עד 366
8 שעון קיץ -1, 0, 1, -1  DST

import time

print (time.localtime());

(time.struct_time(tm_year=2020, tm_mon=9, tm_mday=25, tm_hour=17, tm_min=20, tm_sec=11, tm_wday=4, tm_yday=269, tm_isdst=0

רשימת tuple זו היא מקבילה למבנה struct_time. בדוגמה זו השתמשנו בפונקציה ()time.localtime על מנת להציג את הזמן המקומי, ניתן גם לייבא את הזמן המקומי: 


import time

localtime = time.localtime(time.time())
print ("Local current time :", localtime)

Local current time : time.struct_time(tm_year=2020, tm_mon=9, tm_mday=25, tm_hour=17, tm_min=33, tm_sec=25, tm_wday=4, tm_yday=269, tm_isdst=0

 

הצגת הזמן בפורמט קריא

ניתן לאתחל זמן במספר דרכים, אך קיימת פונקציה ()asctime במודול time בדיוק לשם כך:


import time

localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)

Local current time : Fri Sep 25 17:42:43 2020

 

הצגת לוח שנה חודשי


import calendar

cal = calendar.month(2020, 3)
print ("Here is the calendar:")
print (cal)


Here is the calendar:
March 2020
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

 

מודול הזמן time

מודול זה הוא כנראה מודול הזמן הכי פופולרי שקיים בשפת Python. אלו הן כל הפונקציות שניתן להפעיל במודול זמן time:

פונקציה תאור
time.altzone The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Use this if the daylight is nonzero
([time.asctime([tupletime 'Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008
( )time.clock Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time()
([time.ctime([secs ()Like asctime(localtime(secs)) and without arguments is like asctime
([time.gmtime([secs Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note − t.tm_isdst is always 0
([time.localtime([secs Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules)
(time.mktime(tupletime Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch
(time.sleep(secs Suspends the calling thread for secs seconds
([time.strftime(fmt[,tupletime Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt
('time.strptime(str,fmt = '%a %b %d %H:%M:%S %Y Parses str according to format string fmt and returns the instant in time-tuple format
( )time.time Returns the current time instant, a floating-point number of seconds since the epoch
()time.tzset Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done

 

מודול לוח שנה Calendar

מודול לוח שנה Calendar מספק לנו פונקציות ללוח שנה, כולל פונקציה שתדפיס לנו טקסט של לוח שנה חודשי או שנתי. בתור ברירת מחדל, לוח שנה calendar מציג את יום שני כיום הראשון של השבוע, ויום ראשון כיום האחרון. על מנת לשנות זאת יש להשתמש בפונקציה ()calendar.setfirstweekday.

אלו הן כל הפונקציות שניתן להפעיל במודול לוח שנה Calendar:

פונקציה תאור
calendar.month(year,month,w = 2,l = 1) Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week
( )calendar.firstweekday Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday
(calendar.isleap(year Returns True if year is a leap year; otherwise, False
(calendar.leapdays(y1,y2 (Returns the total number of leap days in the years within range(y1,y2
calendar.month(year,month,w = 2,l = 1) Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.
(calendar.monthcalendar(year,month Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up
(calendar.monthrange(year,month Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12
calendar.prcal(year,w = 2,l = 1,c = 6) Like print calendar.calendar(year,w,l,c).
calendar.prmonth(year,month,w = 2,l = 1) Like print calendar.month(year,month,w,l).
(calendar.setfirstweekday(weekday Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday)
(calendar.timegm(tupletime The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch
(calendar.weekday(year,month,day Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December)

רוצים לשתף את המדריך?

אהבתכם את המדריך? פתר לכם תקלה? הזמינו את כותב המדריך לכוס קפה

גולשים יקרים, התכנים המוצגים באתר נכתבים בהתנדבות מלאה מתוך כוונה להנגיש מידע עבורכם. אם נתקלתם במדריך חינמי שפתר לכם תקלה או לימד אתכם משהו חדש שלא ידעתם, וברצונכם לתגמל את כותב המדריך או סתם להזמין אותו לכוס קפה, הינכם יותר ממוזמנים לתרום.

ניתן לתרום 10, 15, 20 או כל סכום אחר שתרצו באמצעות כרטיס אשראי \ Paypal

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

הזמינו אותי לכוס קפה
buy me coffee

אהבתכם את המדריך? פתר לכם תקלה? הזמינו את כותב המדריך לכוס קפה

גולשים יקרים, רוב התכנים המוצגים באתר נכתבים בהתנדבות מלאה מתוך כוונה להנגיש מידע עבורכם. אם נתקלתם במדריך חינמי שפתר לכם תקלה או לימד אתכם משהו חדש שלא ידעתם, וברצונכם לתגמל את כותב המדריך או סתם להזמין אותו לכוס קפה, הינכם יותר ממוזמנים לתרום.