Master Python Functions and Time Utilities: From Basics to Real-World Code
This article introduces Python functions, demonstrates how to define and call them, and explores essential time-related modules such as time, datetime, calendar, and random, providing clear code examples and output screenshots to help beginners grasp practical usage.
1. Function Overview
In Python, a function groups specific code into a reusable unit, allowing you to encapsulate functionality and call it whenever needed.
2. Function Definition and Invocation
Defining a function creates a tool you can later use; calling the function executes the code inside.
def test():
print('----嘻嘻----')
print('----这是我的第一个函数----')Calling the function runs the defined code.
# Define a function
def test():
print('----嘻嘻----')
print('----这是我的第一个函数----')
# Call the function
test()Result:
Time Functions
Time-related functions are useful for debugging and logging.
1. Get current timestamp: time.time()
import time # import time module
currentTime = time.time()
print("当前时间戳为:", currentTime)2. Get local time tuple: time.localtime(time.time())
import time
localtime = time.localtime(time.time())
print("本地时间为 :", localtime)import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)Extended (datetime module)
1. Date formatting: datetime → string
import datetime
now = datetime.datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S')2. String → datetime
import datetime
t_str = '2019-04-07 16:11:21'
d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
print(d)3. Date comparison using timedelta
The timedelta class represents a time interval and supports arithmetic operations.
import datetime
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)All parameters default to 0 and can be int or float.
import datetime
year = datetime.timedelta(days=365)
t_years = year * 10
new_years = t_years - year
print(t_years)
print(new_years)Date, time and datetime classes also support addition/subtraction with timedelta.
datetime1 = datetime2 + timedelta
timedelta = datetime1 - datetime2Calendar Functions
import calendar
dar = calendar.month(2016, 8)
print("2016年8月份的日历:")
print(dar)Random Number Functions
import random
a = random.uniform(1, 5)
print("a =", a)
b = random.randint(10, 50)
print("b =", b)
c = random.randrange(0, 51, 2)
print("c =", c)3. Summary
The article thoroughly explains Python function definition and invocation, introduces common time‑related functions from the time, datetime, calendar, and random modules, and provides runnable code snippets and output images to help readers practice and master these essential tools.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
