"Day 35 of #100DaysOfPython: Working with Time and Calendar in Python"

🚀 Day 35 of #100DaysOfPython – Working with Date, Time & Calendar 🕒📅 Today’s topic helps us retrieve and manipulate the current date, time, and calendar using Python’s built-in modules — time and calendar. 🕐 1️⃣ Retrieving the Current Time Python provides the time() and localtime() functions to get system time. import time lt = time.localtime(time.time()) print(lt) 🧩 Output example: time.struct_time(tm_year=2022, tm_mon=4, tm_mday=14, tm_hour=10, tm_min=30, ...) 🔹 Attributes of time.struct_time: tm_year → Current year tm_mon → Current month tm_mday → Day of month tm_hour → Hour tm_min → Minute tm_sec → Second tm_wday → Weekday tm_yday → Day of year tm_isdst → Daylight saving flag 🕓 2️⃣ Formatted Time with asctime() The asctime() method returns the current time as a formatted string. import time lt = time.asctime(time.localtime(time.time())) print(lt) ✅ Example Output: Thu Apr 14 10:33:59 2022 🧮 3️⃣ Converting String to Time – strptime() Used to parse strings into time structures. import time tr = time.strptime("26 jun 14", "%d %b %y") print(tr) 📖 Example Output: time.struct_time(tm_year=2014, tm_mon=6, tm_mday=26, ...) 🧭 4️⃣ Formatting Time – strftime() Converts time into a specific string format. import time t = (2014, 6, 26, 17, 3, 38, 1, 48, -1) t = time.mktime(t) print(time.strftime("%d %m %y %H:%M:%S", time.gmtime(t))) ✅ Output: 26 06 14 11:33:38 📆 5️⃣ Python Calendar Module The calendar module allows working with dates, months, and years. import calendar print(calendar.prcal(2023)) 🧠 Common Calendar Functions: Method Description prcal(year) Prints full calendar for a year firstweekday() Returns first weekday (default Monday = 0) isleap(year) Checks if year is leap monthcalendar(year, month) Returns matrix of weeks in month leapdays(y1, y2) Counts leap years between y1 and y2 prmonth(year, month) Prints specific month 🗓️ Example: import calendar print(calendar.isleap(2020)) # True print(calendar.monthcalendar(2022, 6)) calendar.prmonth(2022, 5) ✨ In Short: time → retrieves and formats time strptime / strftime → convert between strings & time calendar → helps print and analyze calendars 💬 Which one do you use most often — datetime, time, or calendar? #Python #100DaysOfCode #LearningPython #PythonProgramming #DateTime #Calendar

To view or add a comment, sign in

Explore content categories