التعامل مع التواريخ والوقت في بايثون: دليل شامل للمبتدئين

مرحباً بك في عالم التواريخ والوقت في بايثون! في عالم البرمجة، غالباً ما نحتاج إلى التعامل مع البيانات الزمنية، مثل تسجيل وقت إنشاء ملف، حساب عمر المستخدم، أو جدولة المهام. في هذا الدرس، سنتعلم كيفية التعامل مع التواريخ والوقت بسهولة باستخدام المكتبة القياسية datetime في بايثون.

استيراد مكتبة datetime

قبل أن نبدأ، نحتاج إلى استيراد المكتبة التي تحتوي على الأدوات التي سنستخدمها. المكتبة تسمى datetime، وهي جزء من المكتبات القياسية في بايثون، مما يعني أنها مثبتة مسبقاً ولا تحتاج إلى تثبيت إضافي.

# Import the entire library
import datetime

# Or import the classes we need directly (preferred method)
from datetime import datetime, date, time, timedelta

في الأمثلة القادمة، سنفترض أننا استخدمنا الطريقة الثانية (from datetime import ...) لأنها تجعل الكود أكثر نظافة ووضوحاً.

إنشاء Objects التاريخ والوقت

المكتبة datetime توفر لنا عدة Classes للتعامل مع أنواع مختلفة من البيانات الزمنية. دعنا نتعرف على الأساسيات:

1. التاريخ فقط (date):

from datetime import date

# Create a specific date (year, month, day)
my_birthday = date(1995, 8, 15)
print(my_birthday)  # Will print: 1995-08-15

# Get today's date
today = date.today()
print("Today's date is:", today)

2. الوقت فقط (time):

from datetime import time

# Create a specific time (hour, minute, second)
meeting_time = time(14, 30, 0)  # 2:30 PM
print(meeting_time)  # Will print: 14:30:00

lunch_time = time(12, 0)  # Seconds can be omitted
print(lunch_time)  # Will print: 12:00:00

3. التاريخ والوقت معاً (datetime): هذه هي الـ Class الأكثر استخداماً، حيث تجمع بين التاريخ والوقت في Object واحد.

from datetime import datetime

# Create a specific date and time
event_start = datetime(2023, 10, 5, 9, 0, 0)  # (year, month, day, hour, minute, second)
print(event_start)  # Will print: 2023-10-05 09:00:00

# Get the current date and time
now = datetime.now()
print("Current date and time:", now)

تنسيق وعرض التواريخ (strftime)

التنسيق الافتراضي للتاريخ (YYYY-MM-DD) قد لا يناسب كل الحالات. لحسن الحظ، يمكننا استخدام الدالة strftime() لتنسيق التاريخ والوقت بأي طريقة نريدها.

from datetime import datetime

now = datetime.now()

# Date formatting
print(now.strftime("%Y/%m/%d"))      # 2023/10/05
print(now.strftime("%d-%m-%Y"))      # 05-10-2023
print(now.strftime("%A, %d %B %Y"))  # Thursday, 05 October 2023 (will appear in English)

# Time formatting
print(now.strftime("%H:%M:%S"))      # 14:30:45 (24-hour format)
print(now.strftime("%I:%M %p"))      # 02:30 PM (12-hour format with AM/PM)

# Combined formatting
full_format = now.strftime("Today is %A %d %B %Y, and the time is %I:%M %p")
print(full_format)

رموز التنسيق الشائعة:

  • %Y: السنة بأربع أرقام (مثل 2023)
  • %y: السنة برقمين (مثل 23)
  • %m: الشهر برقمين (01 إلى 12)
  • %B: اسم الشهر كاملاً (بالإنجليزية)
  • %b: اسم الشهر المختصر (بالإنجليزية)
  • %d: اليوم من الشهر (01 إلى 31)
  • %A: اسم اليوم كاملاً (بالإنجليزية)
  • %H: الساعة (00 إلى 23)
  • %I: الساعة (01 إلى 12)
  • %M: الدقيقة (00 إلى 59)
  • %S: الثانية (00 إلى 59)
  • %p: AM أو PM

تحويل النص إلى تاريخ (strptime)

ماذا لو كان لدينا تاريخ على شكل نص (string) وأردنا تحويله إلى Object datetime للتعامل معه برمجياً؟ هنا تأتي دالة strptime() للإنقاذ!

from datetime import datetime

# We have a date as a string
date_string = "25-12-2023 20:30"

# Convert it to a datetime object
# We must specify the format matching the original text
christmas_eve = datetime.strptime(date_string, "%d-%m-%Y %H:%M")
print(christmas_eve)  # Will print as a datetime object: 2023-12-25 20:30:00

# Now we can handle it like any other datetime object
print("Today is:", christmas_eve.strftime("%A"))

العمليات الحسابية على التواريخ (timedelta)

أحد أكثر الأشياء المفيدة في التعامل مع التواريخ هو القدرة على إجراء عمليات حسابية عليها، مثل إضافة أيام أو حساب الفرق بين تاريخين.

from datetime import datetime, timedelta

today = datetime.now()
print("Today:", today.strftime("%Y-%m-%d"))

# Add 7 days (one week)
next_week = today + timedelta(days=7)
print("After a week:", next_week.strftime("%Y-%m-%d"))

# Subtract 3 days
three_days_ago = today - timedelta(days=3)
print("Three days ago:", three_days_ago.strftime("%Y-%m-%d"))

# Add a mix of time units
future_date = today + timedelta(weeks=2, days=3, hours=5)
print("Future date:", future_date)

# Calculate the difference between two dates
date1 = datetime(2023, 12, 25)
date2 = datetime(2023, 12, 20)
difference = date1 - date2  # Result will be a timedelta object
print("The difference between the dates is:", difference.days, "days")

مثال تطبيقي بسيط: حساب عمر الشخص

لنجمع ما تعلمناه في مثال عملي بسيط:

from datetime import date

# Person's birth date
birth_date = date(2000, 5, 10)
today = date.today()

# Calculate age in days
age_in_days = (today - birth_date).days
print(f"Your age in days: {age_in_days} days")

# Convert days to approximate years
age_in_years = age_in_days // 365  # Use integer division
print(f"Your approximate age: {age_in_years} years")

ملخص الدرس

تعلمنا في هذا الدرس الأساسيات القوية للتعامل مع التواريخ والوقت في بايثون:

  • كيفية استيراد واستخدام مكتبة datetime
  • إنشاء Objects date، time، و datetime
  • تنسيق عرض التواريخ باستخدام strftime()
  • تحويل النصوص إلى تواريخ باستخدام strptime()
  • إجراء العمليات الحسابية باستخدام timedelta

تذكر أن الممارسة هي مفتاح الإتقان! جرب إنشاء برنامج بسيط يسجل وقت بداية ونهاية تنفيذ مهمة معينة، ثم يحسب المدة التي استغرقتها.