Here's your Telegram post for Day 15 of the Python learning series!
---
🚀 Day 15: Dive into the world of Python Libraries! Today, we're unlocking the power of the `requests` library. Ever wanted your Python scripts to interact with websites, fetch data, or send information? `requests` makes web interactions incredibly simple and elegant. It's an indispensable tool for web scraping, API interactions, and much more. Let's make some requests! 🌐
```python
import requests # Import the requests library
# Define the URL for a public API endpoint
# This API provides fake data for testing purposes
url = "https://jsonplaceholder.typicode.com/todos/1"
# Make a GET request to the URL
response = requests.get(url)
# Print the HTTP status code
print(f"Status Code: {response.status_code}")
# Check if the request was successful (status code 200 indicates success)
if response.status_code == 200:
# Print the JSON response content
# .json() method automatically parses the JSON response into a Python dictionary
print("Response JSON:")
print(response.json())
else:
print(f"Request failed with status code {response.status_code}")
```
Output example:
```
Status Code: 200
Response JSON:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
```
💡 **Challenge Time!** Try modifying the `url` in the code to `https://jsonplaceholder.typicode.com/posts/2`. What kind of data do you get back? Can you also try to print `response.headers` to see the HTTP response headers? Share your findings! 👇
---
---
🚀 Day 15: Dive into the world of Python Libraries! Today, we're unlocking the power of the `requests` library. Ever wanted your Python scripts to interact with websites, fetch data, or send information? `requests` makes web interactions incredibly simple and elegant. It's an indispensable tool for web scraping, API interactions, and much more. Let's make some requests! 🌐
```python
import requests # Import the requests library
# Define the URL for a public API endpoint
# This API provides fake data for testing purposes
url = "https://jsonplaceholder.typicode.com/todos/1"
# Make a GET request to the URL
response = requests.get(url)
# Print the HTTP status code
print(f"Status Code: {response.status_code}")
# Check if the request was successful (status code 200 indicates success)
if response.status_code == 200:
# Print the JSON response content
# .json() method automatically parses the JSON response into a Python dictionary
print("Response JSON:")
print(response.json())
else:
print(f"Request failed with status code {response.status_code}")
```
Output example:
```
Status Code: 200
Response JSON:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
```
💡 **Challenge Time!** Try modifying the `url` in the code to `https://jsonplaceholder.typicode.com/posts/2`. What kind of data do you get back? Can you also try to print `response.headers` to see the HTTP response headers? Share your findings! 👇
---
What is the primary purpose of the `requests` library in Python?
Anonymous Quiz
0%
To create graphical user interfaces (GUIs).
0%
To perform mathematical computations.
0%
To make HTTP requests to web servers.
0%
To manage database connections.
Here's your Telegram post for the Python learning series:
---
👋 Hey Python learners!
Day 16 is here, and we're diving into the exciting world of **Working with APIs**! 🌐 Ever wondered how apps like weather apps or social media feeds get their data? It's all thanks to APIs (Application Programming Interfaces)! They allow different software applications to communicate with each other. In Python, the `requests` library is your best friend for interacting with web APIs. Today, we'll learn how to fetch data from an API using a simple GET request. Let's get connected! 📡🚀
```python
import requests
# Define the API endpoint URL
url = "https://api.chucknorris.io/jokes/random"
try:
# Make a GET request to the API
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Extract the joke from the data
joke = data['value']
print("Chuck Norris Joke:")
print(joke)
else:
print(f"Error fetching joke: {response.status_code}")
print(response.text) # Print error details if available
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
```
Output example:
```
Chuck Norris Joke:
Chuck Norris taught a blind man to see. Not to read, but to see.
```
**Challenge:**
Try fetching a random Kanye West quote from `https://api.kanye.rest/` and print it out! 🤔 You'll notice the structure of the JSON response might be slightly different. Good luck!
---
---
👋 Hey Python learners!
Day 16 is here, and we're diving into the exciting world of **Working with APIs**! 🌐 Ever wondered how apps like weather apps or social media feeds get their data? It's all thanks to APIs (Application Programming Interfaces)! They allow different software applications to communicate with each other. In Python, the `requests` library is your best friend for interacting with web APIs. Today, we'll learn how to fetch data from an API using a simple GET request. Let's get connected! 📡🚀
```python
import requests
# Define the API endpoint URL
url = "https://api.chucknorris.io/jokes/random"
try:
# Make a GET request to the API
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Extract the joke from the data
joke = data['value']
print("Chuck Norris Joke:")
print(joke)
else:
print(f"Error fetching joke: {response.status_code}")
print(response.text) # Print error details if available
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
```
Output example:
```
Chuck Norris Joke:
Chuck Norris taught a blind man to see. Not to read, but to see.
```
**Challenge:**
Try fetching a random Kanye West quote from `https://api.kanye.rest/` and print it out! 🤔 You'll notice the structure of the JSON response might be slightly different. Good luck!
---
Which `requests` library method is typically used to retrieve data from a web API?
Anonymous Quiz
0%
0%
requests.send()
0%
requests.get()
0%
requests.fetch()
Here's your Telegram post for Day 17!
---
Hey Pythonistas! 👋 Day 17 is here, and we're diving into a cornerstone of modern web development and data exchange: **JSON** (JavaScript Object Notation). 🌐 It's the lightweight, human-readable format used extensively for APIs, configuration files, and more. Python makes handling JSON incredibly easy with its built-in `json` module. You'll learn how to convert Python dictionaries/lists to JSON strings and files, and vice versa. Let's unlock the power of data interchange! 🚀
```python
import json
import os
# --- Part 1: Python objects to JSON strings (serialization) ---
# A Python dictionary
user_data = {
"name": "Alex",
"age": 28,
"is_active": True,
"skills": ["Python", "API", "Databases"],
"preferences": {"theme": "dark", "notifications": True},
"last_login": None
}
# Convert Python dict to JSON string (dumps = "dump string")
# 'indent=4' makes the JSON output pretty-printed for readability
json_string = json.dumps(user_data, indent=4)
print("--- Python Dictionary to JSON String ---")
print(json_string)
# --- Part 2: JSON strings to Python objects (deserialization) ---
# A JSON string
json_text = '''
{
"product": "Wireless Mouse",
"price": 25.99,
"available": true,
"ratings": 4.5
}
'''
# Convert JSON string to Python dictionary (loads = "load string")
product_dict = json.loads(json_text)
print("n--- JSON String to Python Dictionary ---")
print(f"Product: {product_dict['product']}")
print(f"Price: ${product_dict['price']}")
print(f"Is available: {product_dict['available']}")
print(f"Type of product_dict: {type(product_dict)}")
# --- Part 3: Python objects to JSON files (serialization to file) ---
file_name = "my_data.json"
config_data = {
"app_name": "MyCoolApp",
"version": "1.0.0",
"settings": {
"log_level": "INFO",
"max_connections": 100
}
}
# Write Python dict to a JSON file (dump = "dump to file")
with open(file_name, 'w') as f:
json.dump(config_data, f, indent=4)
print(f"n--- Python Dictionary written to '{file_name}' ---")
# --- Part 4: JSON files to Python objects (deserialization from file) ---
# Read JSON from a file into a Python dictionary (load = "load from file")
if os.path.exists(file_name):
with open(file_name, 'r') as f:
loaded_config = json.load(f)
print(f"--- JSON from '{file_name}' loaded into Python Dictionary ---")
print(f"App Name: {loaded_config['app_name']}")
print(f"Log Level: {loaded_config['settings']['log_level']}")
# Clean up the created file
os.remove(file_name)
print(f"'{file_name}' removed.")
else:
print(f"Error: '{file_name}' not found for loading.")
```
Output example:
```
--- Python Dictionary to JSON String ---
{
"name": "Alex",
"age": 28,
"is_active": true,
"skills": [
"Python",
"API",
"Databases"
],
"preferences": {
"theme": "dark",
"notifications": true
},
"last_login": null
}
--- JSON String to Python Dictionary ---
Product: Wireless Mouse
Price: $25.99
Is available: True
Type of product_dict: <class 'dict'>
--- Python Dictionary written to 'my_data.json' ---
--- JSON from 'my_data.json' loaded into Python Dictionary ---
App Name: MyCoolApp
Log Level: INFO
'my_data.json' removed.
```
### Your Challenge! 🧠💡
Create a list of Python dictionaries, where each dictionary represents an employee with keys like `id`, `name`, `department`, and `salary`. Convert this list into a JSON string and print it. Then, write this same data to a file named `employees.json`. Finally, load `employees.json` back into a Python list and print the names of all employees who work in the "Marketing" department. Don't forget to clean up the file!
---
### Quiz Question ❓
---
Hey Pythonistas! 👋 Day 17 is here, and we're diving into a cornerstone of modern web development and data exchange: **JSON** (JavaScript Object Notation). 🌐 It's the lightweight, human-readable format used extensively for APIs, configuration files, and more. Python makes handling JSON incredibly easy with its built-in `json` module. You'll learn how to convert Python dictionaries/lists to JSON strings and files, and vice versa. Let's unlock the power of data interchange! 🚀
```python
import json
import os
# --- Part 1: Python objects to JSON strings (serialization) ---
# A Python dictionary
user_data = {
"name": "Alex",
"age": 28,
"is_active": True,
"skills": ["Python", "API", "Databases"],
"preferences": {"theme": "dark", "notifications": True},
"last_login": None
}
# Convert Python dict to JSON string (dumps = "dump string")
# 'indent=4' makes the JSON output pretty-printed for readability
json_string = json.dumps(user_data, indent=4)
print("--- Python Dictionary to JSON String ---")
print(json_string)
# --- Part 2: JSON strings to Python objects (deserialization) ---
# A JSON string
json_text = '''
{
"product": "Wireless Mouse",
"price": 25.99,
"available": true,
"ratings": 4.5
}
'''
# Convert JSON string to Python dictionary (loads = "load string")
product_dict = json.loads(json_text)
print("n--- JSON String to Python Dictionary ---")
print(f"Product: {product_dict['product']}")
print(f"Price: ${product_dict['price']}")
print(f"Is available: {product_dict['available']}")
print(f"Type of product_dict: {type(product_dict)}")
# --- Part 3: Python objects to JSON files (serialization to file) ---
file_name = "my_data.json"
config_data = {
"app_name": "MyCoolApp",
"version": "1.0.0",
"settings": {
"log_level": "INFO",
"max_connections": 100
}
}
# Write Python dict to a JSON file (dump = "dump to file")
with open(file_name, 'w') as f:
json.dump(config_data, f, indent=4)
print(f"n--- Python Dictionary written to '{file_name}' ---")
# --- Part 4: JSON files to Python objects (deserialization from file) ---
# Read JSON from a file into a Python dictionary (load = "load from file")
if os.path.exists(file_name):
with open(file_name, 'r') as f:
loaded_config = json.load(f)
print(f"--- JSON from '{file_name}' loaded into Python Dictionary ---")
print(f"App Name: {loaded_config['app_name']}")
print(f"Log Level: {loaded_config['settings']['log_level']}")
# Clean up the created file
os.remove(file_name)
print(f"'{file_name}' removed.")
else:
print(f"Error: '{file_name}' not found for loading.")
```
Output example:
```
--- Python Dictionary to JSON String ---
{
"name": "Alex",
"age": 28,
"is_active": true,
"skills": [
"Python",
"API",
"Databases"
],
"preferences": {
"theme": "dark",
"notifications": true
},
"last_login": null
}
--- JSON String to Python Dictionary ---
Product: Wireless Mouse
Price: $25.99
Is available: True
Type of product_dict: <class 'dict'>
--- Python Dictionary written to 'my_data.json' ---
--- JSON from 'my_data.json' loaded into Python Dictionary ---
App Name: MyCoolApp
Log Level: INFO
'my_data.json' removed.
```
### Your Challenge! 🧠💡
Create a list of Python dictionaries, where each dictionary represents an employee with keys like `id`, `name`, `department`, and `salary`. Convert this list into a JSON string and print it. Then, write this same data to a file named `employees.json`. Finally, load `employees.json` back into a Python list and print the names of all employees who work in the "Marketing" department. Don't forget to clean up the file!
---
### Quiz Question ❓
Which of the following Python data types is *NOT* directly equivalent to a JSON data type?
Anonymous Quiz
0%
String
0%
List
0%
Tuple
100%
Dictionary
Here's your Telegram post for Day 18: Regular Expressions!
---
🚀 Day 18: Regular Expressions! 🤯 Get ready to master the art of text pattern matching with Python's powerful `re` module. Regular Expressions (RegEx) are essential for searching, extracting, and manipulating text based on complex patterns. Whether it's validating user input or parsing logs, RegEx is your go-to tool. Let's dive into finding patterns today! 🔍📝
```python
import re
text = "Hello Python learners! Today is Day 18. We're diving into Regular Expressions. Find all words, numbers, and underscores!"
# Pattern 1: Find all "words" (alphanumeric characters + underscore)
# w matches any word character (a-z, A-Z, 0-9, _)
# + matches one or more occurrences of the preceding character/group
pattern_words = r'w+'
found_words = re.findall(pattern_words, text)
print("Found 'words':", found_words)
# Pattern 2: Find all numbers
# d matches any digit (0-9)
pattern_numbers = r'd+'
found_numbers = re.findall(pattern_numbers, text)
print("Found numbers:", found_numbers)
```
Output example:
```
Found 'words': ['Hello', 'Python', 'learners', 'Today', 'is', 'Day', '18', 'We', 're', 'diving', 'into', 'Regular', 'Expressions', 'Find', 'all', 'words', 'numbers', 'and', 'underscores']
Found numbers: ['18']
```
💡 **Small Challenge:** Can you modify the code to find all words in the `text` variable that *start* with 'R' or 'r'? (Hint: Look into `^` for start of string/line and character sets `[]`!)
---
---
🚀 Day 18: Regular Expressions! 🤯 Get ready to master the art of text pattern matching with Python's powerful `re` module. Regular Expressions (RegEx) are essential for searching, extracting, and manipulating text based on complex patterns. Whether it's validating user input or parsing logs, RegEx is your go-to tool. Let's dive into finding patterns today! 🔍📝
```python
import re
text = "Hello Python learners! Today is Day 18. We're diving into Regular Expressions. Find all words, numbers, and underscores!"
# Pattern 1: Find all "words" (alphanumeric characters + underscore)
# w matches any word character (a-z, A-Z, 0-9, _)
# + matches one or more occurrences of the preceding character/group
pattern_words = r'w+'
found_words = re.findall(pattern_words, text)
print("Found 'words':", found_words)
# Pattern 2: Find all numbers
# d matches any digit (0-9)
pattern_numbers = r'd+'
found_numbers = re.findall(pattern_numbers, text)
print("Found numbers:", found_numbers)
```
Output example:
```
Found 'words': ['Hello', 'Python', 'learners', 'Today', 'is', 'Day', '18', 'We', 're', 'diving', 'into', 'Regular', 'Expressions', 'Find', 'all', 'words', 'numbers', 'and', 'underscores']
Found numbers: ['18']
```
💡 **Small Challenge:** Can you modify the code to find all words in the `text` variable that *start* with 'R' or 'r'? (Hint: Look into `^` for start of string/line and character sets `[]`!)
---
Which `re` module function is typically used to find *all* non-overlapping matches of a pattern in a string and return them as a list of strings?
Anonymous Quiz
0%
re.findall()
0%
0%
re.match()
0%
re.sub()
🚀 Day 19: Mastering Python Virtual Environments! 🚀
Ever faced "dependency hell" where one project needs a different package version than another? Say goodbye to conflicts! Today, we're diving into virtual environments – your secret weapon for isolating project dependencies. Keep your projects clean, organized, and conflict-free. Let's set up our isolated workspaces! ✨📦
Here's how you use them:
```python
# 1. Create a virtual environment (replace 'my_project_env' with your desired name)
python -m venv my_project_env
# 2. Activate the virtual environment
# On macOS/Linux:
source my_project_env/bin/activate
# On Windows (Command Prompt):
my_project_envScriptsactivate
# On Windows (PowerShell):
my_project_envScriptsActivate.ps1
# 3. Install a package inside the activated environment
pip install requests
# 4. See installed packages (it will only show packages in this venv)
pip list
# 5. Deactivate the virtual environment
deactivate
```
Output example:
```
(base) user@host:~$ python -m venv my_project_env
(base) user@host:~$ source my_project_env/bin/activate
(my_project_env) user@host:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 kB 390.6 kB/s eta 0:00:00
Collecting idna<4,>=2.5
Downloading idna-3.6-py3-none-any.whl (61 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.8/61.8 kB 403.6 kB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
Downloading charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (119 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 119.8/119.8 kB 506.7 kB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
Downloading urllib3-2.1.0-py3-none-any.whl (104 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 104.5/104.5 kB 558.1 kB/s eta 0:00:00
Collecting certifi>=2017.4.17
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 162.5/162.5 kB 588.6 kB/s eta 0:00:00
Installing collected packages: idna, charset-normalizer, urllib3, certifi, requests
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(my_project_env) user@host:~$ pip list
Package Version
---------------- ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
setuptools 68.2.2
urllib3 2.1.0
(my_project_env) user@host:~$ deactivate
(base) user@host:~$
```
💡 **Your Challenge:**
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library using `pip`.
4. Confirm `numpy` is listed using `pip list`.
5. Deactivate your environment.
Share your success in the comments! 🎉
Ever faced "dependency hell" where one project needs a different package version than another? Say goodbye to conflicts! Today, we're diving into virtual environments – your secret weapon for isolating project dependencies. Keep your projects clean, organized, and conflict-free. Let's set up our isolated workspaces! ✨📦
Here's how you use them:
```python
# 1. Create a virtual environment (replace 'my_project_env' with your desired name)
python -m venv my_project_env
# 2. Activate the virtual environment
# On macOS/Linux:
source my_project_env/bin/activate
# On Windows (Command Prompt):
my_project_envScriptsactivate
# On Windows (PowerShell):
my_project_envScriptsActivate.ps1
# 3. Install a package inside the activated environment
pip install requests
# 4. See installed packages (it will only show packages in this venv)
pip list
# 5. Deactivate the virtual environment
deactivate
```
Output example:
```
(base) user@host:~$ python -m venv my_project_env
(base) user@host:~$ source my_project_env/bin/activate
(my_project_env) user@host:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 kB 390.6 kB/s eta 0:00:00
Collecting idna<4,>=2.5
Downloading idna-3.6-py3-none-any.whl (61 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.8/61.8 kB 403.6 kB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
Downloading charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (119 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 119.8/119.8 kB 506.7 kB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
Downloading urllib3-2.1.0-py3-none-any.whl (104 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 104.5/104.5 kB 558.1 kB/s eta 0:00:00
Collecting certifi>=2017.4.17
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 162.5/162.5 kB 588.6 kB/s eta 0:00:00
Installing collected packages: idna, charset-normalizer, urllib3, certifi, requests
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(my_project_env) user@host:~$ pip list
Package Version
---------------- ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
setuptools 68.2.2
urllib3 2.1.0
(my_project_env) user@host:~$ deactivate
(base) user@host:~$
```
💡 **Your Challenge:**
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library using `pip`.
4. Confirm `numpy` is listed using `pip list`.
5. Deactivate your environment.
Share your success in the comments! 🎉
What is the primary purpose of using Python virtual environments?
Anonymous Quiz
0%
To speed up the execution of Python scripts.
0%
To create isolated environments for different projects to manage their dependencies independently.
0%
To globally install all Python packages on your system.
0%
To automatically back up your Python code to the cloud.
Here's your Telegram post and quiz question!
---
🚀 Day 20: Mastering Dates & Times in Python! 📅⏰
Time flies, but you can definitely manage it in your Python programs! Today, we're diving into the powerful `datetime` module to handle dates and times with ease. Learn to fetch the current moment, format it just how you like, and even parse date strings back into objects. Get ready to conquer time! 🗓️✨
```python
import datetime
# Get current date and time
current_dt = datetime.datetime.now()
print(f"Current Date & Time: {current_dt}")
# Format the date and time into a readable string
formatted_dt = current_dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date & Time: {formatted_dt}")
# Format for a different style (e.g., Day, Month Day, Year Hour:Minute AM/PM)
custom_format = current_dt.strftime("%A, %B %d, %Y %I:%M %p")
print(f"Custom Formatted: {custom_format}")
# Parse a string into a datetime object
date_string = "2024-07-20 14:30:00"
parsed_dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date & Time: {parsed_dt}")
```
Output example:
```
Current Date & Time: 2023-10-27 10:30:45.123456
Formatted Date & Time: 2023-10-27 10:30:45
Custom Formatted: Friday, October 27, 2023 10:30 AM
Parsed Date & Time: 2024-07-20 14:30:00
```
Small challenge:
Can you create a `datetime` object for January 1st, 2025, at 00:00:00, and then format it to display as "Wednesday, Jan 1, 2025"? Share your code! 👇
---
---
🚀 Day 20: Mastering Dates & Times in Python! 📅⏰
Time flies, but you can definitely manage it in your Python programs! Today, we're diving into the powerful `datetime` module to handle dates and times with ease. Learn to fetch the current moment, format it just how you like, and even parse date strings back into objects. Get ready to conquer time! 🗓️✨
```python
import datetime
# Get current date and time
current_dt = datetime.datetime.now()
print(f"Current Date & Time: {current_dt}")
# Format the date and time into a readable string
formatted_dt = current_dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date & Time: {formatted_dt}")
# Format for a different style (e.g., Day, Month Day, Year Hour:Minute AM/PM)
custom_format = current_dt.strftime("%A, %B %d, %Y %I:%M %p")
print(f"Custom Formatted: {custom_format}")
# Parse a string into a datetime object
date_string = "2024-07-20 14:30:00"
parsed_dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date & Time: {parsed_dt}")
```
Output example:
```
Current Date & Time: 2023-10-27 10:30:45.123456
Formatted Date & Time: 2023-10-27 10:30:45
Custom Formatted: Friday, October 27, 2023 10:30 AM
Parsed Date & Time: 2024-07-20 14:30:00
```
Small challenge:
Can you create a `datetime` object for January 1st, 2025, at 00:00:00, and then format it to display as "Wednesday, Jan 1, 2025"? Share your code! 👇
---
Which `strftime` format code would you use to get the full weekday name (e.g., 'Monday') from a datetime object?
Anonymous Quiz
0%
"%w"
0%
"%a"
0%
"%A"
0%
"%W"
Here's your Telegram post for Day 21 on Decorators!
---
**Day 21: Decorators! 🎩✨**
Today we're diving into one of Python's most elegant and powerful features. Decorators allow you to modify or extend the functionality of a function or method without explicitly changing its source code. Think of them as wrappers! They're super useful for logging, authentication, performance measurement, and more. Get ready to elevate your functions! 🚀
```python
import time
# Our first decorator: a simple timer!
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"⏱️ '{func.__name__}' ran in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Applying the decorator using the '@' syntax
@timer
def simulate_task(duration):
"""Simulates a task that takes some time."""
print(f"Executing task for {duration} seconds...")
time.sleep(duration)
print("Task completed!")
return f"Simulated task finished in {duration}s"
@timer
def calculate_sum(a, b):
"""Calculates the sum of two numbers."""
time.sleep(0.05) # A tiny delay
return a + b
print("--- Calling decorated functions ---")
simulate_task(1.5)
simulate_task(0.8)
sum_result = calculate_sum(10, 20)
print(f"Result of calculation: {sum_result}")
```
Output example:
```
--- Calling decorated functions ---
Executing task for 1.5 seconds...
Task completed!
⏱️ 'simulate_task' ran in 1.5034 seconds.
Executing task for 0.8 seconds...
Task completed!
⏱️ 'simulate_task' ran in 0.8012 seconds.
⏱️ 'calculate_sum' ran in 0.0510 seconds.
Result of calculation: 30
```
**Small challenge:**
Can you modify the `timer` decorator to also print the arguments (`args` and `kwargs`) that the decorated function was called with? Hint: Access them inside the `wrapper` function! 🧐 Good luck!
---
---
**Day 21: Decorators! 🎩✨**
Today we're diving into one of Python's most elegant and powerful features. Decorators allow you to modify or extend the functionality of a function or method without explicitly changing its source code. Think of them as wrappers! They're super useful for logging, authentication, performance measurement, and more. Get ready to elevate your functions! 🚀
```python
import time
# Our first decorator: a simple timer!
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"⏱️ '{func.__name__}' ran in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Applying the decorator using the '@' syntax
@timer
def simulate_task(duration):
"""Simulates a task that takes some time."""
print(f"Executing task for {duration} seconds...")
time.sleep(duration)
print("Task completed!")
return f"Simulated task finished in {duration}s"
@timer
def calculate_sum(a, b):
"""Calculates the sum of two numbers."""
time.sleep(0.05) # A tiny delay
return a + b
print("--- Calling decorated functions ---")
simulate_task(1.5)
simulate_task(0.8)
sum_result = calculate_sum(10, 20)
print(f"Result of calculation: {sum_result}")
```
Output example:
```
--- Calling decorated functions ---
Executing task for 1.5 seconds...
Task completed!
⏱️ 'simulate_task' ran in 1.5034 seconds.
Executing task for 0.8 seconds...
Task completed!
⏱️ 'simulate_task' ran in 0.8012 seconds.
⏱️ 'calculate_sum' ran in 0.0510 seconds.
Result of calculation: 30
```
**Small challenge:**
Can you modify the `timer` decorator to also print the arguments (`args` and `kwargs`) that the decorated function was called with? Hint: Access them inside the `wrapper` function! 🧐 Good luck!
---