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 utilities—including time, datetime, calendar, and random modules—through clear explanations and runnable code snippets, helping readers build a solid foundation for practical Python programming.
1. Function Overview
In Python, a function groups specific code into a reusable unit that can be invoked whenever needed.
2. Function Definition and Invocation
A function definition creates a tool that performs a particular task.
def test():
print('----嘻嘻----')
print('----这是我的第一个函数----')Defining a function alone does not execute it; it must be called.
# Define a function
def test():
print('----嘻嘻----')
print('----这是我的第一个函数----')
# Call the function
test()Result:
Python’s rich set of built‑in functions contributes to its popularity among developers.
Time Functions
Debugging often requires timestamp output, which is provided by time‑related functions.
1. Get current timestamp: time.time()
import time # import time module
currentTime = time.time()
print("当前时间戳为:", currentTime)Result:
2. Get local time tuple: time.localtime(time.time())
import time
localtime = time.localtime(time.time())
print("本地时间为 :", localtime)Result:
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)Result:
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)Result:
strptime is a static method of the datetime class.
3. Date comparison using timedelta
The timedelta class represents a time interval and supports arithmetic.
import datetime
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0)All parameters default to 0; you can access attributes such as days or seconds.
import datetime
year = datetime.timedelta(days=365)
t_years = year * 10
new_years = t_years - year
print(t_years)
print(new_years)Result:
date, time, and datetime classes also support addition and subtraction with timedelta, enabling convenient operations.
datetime1 = datetime2 + timedelta
timedelta = datetime1 - datetime2Calendar Functions
import calendar
dar = calendar.month(2016, 8)
print("2016年8月份的日历:")
print(dar)Result:
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)Result:
3. Summary
This article detailed Python function definitions and calls, introduced common time‑related functions, and provided practical code examples to help readers better understand and apply functions in Python programming.
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.
