"Mastering Date and Time in Python with datetime Module"

🚀 **Day 34 of #100DaysOfPython – Date and Time in Python** 🕒 Python provides the **`datetime`** module to handle dates and times efficiently. Let’s explore the most useful features with simple examples 👇 --- ### 🧭 1️⃣ Importing the datetime Module ```python import datetime ``` This gives access to classes like `date`, `time`, `datetime`, and `timedelta`. --- ### 📅 2️⃣ Working with Dates ```python from datetime import date today = date.today() print("Today's date:", today) specific_date = date(2024, 2, 16) print("Specific date:", specific_date) ``` ✅ You can extract parts of a date: ```python print("Year:", today.year) print("Month:", today.month) print("Day:", today.day) ``` ✅ To find the weekday: ```python print("Weekday (0=Mon):", today.weekday()) print("ISO Weekday (1=Mon):", today.isoweekday()) ``` --- ### ⏰ 3️⃣ Working with Time ```python from datetime import time specific_time = time(14, 30, 15) print("Specific time:", specific_time) print("Hour:", specific_time.hour) print("Minute:", specific_time.minute) print("Second:", specific_time.second) ``` --- ### 📆 4️⃣ Date and Time Together ```python from datetime import datetime now = datetime.now() print("Current date and time:", now) specific_datetime = datetime(2024, 2, 16, 14, 30, 15) print("Specific date and time:", specific_datetime) ``` ✅ Extract individual parts: ```python print("Year:", now.year) print("Month:", now.month) print("Day:", now.day) print("Hour:", now.hour) print("Minute:", now.minute) print("Second:", now.second) ``` --- ### 🕓 5️⃣ Formatting Dates & Times ```python formatted_date = now.strftime("%Y-%m-%d") formatted_time = now.strftime("%H:%M:%S") formatted_datetime = now.strftime("%d-%b-%Y %I:%M %p") print("Formatted Date:", formatted_date) print("Formatted Time:", formatted_time) print("Formatted Date and Time:", formatted_datetime) ``` 📘 Example: `%Y` = Year, `%m` = Month, `%d` = Day, `%H` = Hour, `%M` = Minute, `%S` = Second, `%p` = AM/PM --- ### 🔁 6️⃣ Parsing Strings into Dates ```python from datetime import datetime date_string = "16-02-2024 14:30" parsed_date = datetime.strptime(date_string, "%d-%m-%Y %H:%M") print("Parsed Date and Time:", parsed_date) ``` --- ### ⏳ 7️⃣ Date and Time Arithmetic ```python from datetime import timedelta from datetime import date, datetime today = date.today() now = datetime.now() future_date = today + timedelta(days=7) past_date = today - timedelta(days=3) future_time = now + timedelta(hours=2) print("Date after 7 days:", future_date) print("Date 3 days ago:", past_date) print("Time after 2 hours:", future_time) ``` --- ✨ **In short:** - `date` → handles calendar dates - `time` → handles time only - `datetime` → combines both - `timedelta` → does date/time math 💬 What’s the most common date format you use in your projects? #Python #100DaysOfCode #PythonProgramming #LearningPython #DateTime

To view or add a comment, sign in

Explore content categories