Python技术问询:如何截取字符串字符、去除datetime输出的毫秒
Hey there! Let's break down your two Python questions clearly, especially since you mentioned you're a total beginner. 😊
The go-to way to grab parts of a string in Python is slicing—it's super flexible and easy to use once you get the hang of the syntax:
your_string[start_index:end_index:step]
Here's what each part means:
start_index: Optional, defaults to 0 (the first character of the string)end_index: Optional, defaults to the end of the string, but note that this character isn't included in the resultstep: Optional, defaults to 1 (meaning we take every character in between)
Let's use examples to make this concrete:
my_string = "Hello Python Newbie" # Grab the first 5 characters print(my_string[:5]) # Output: Hello # Grab everything from index 6 onwards print(my_string[6:]) # Output: Python Newbie # Grab just "Python" (from index 6 to 12, not including 12) print(my_string[6:12]) # Output: Python # Grab the last 6 characters using negative indexing print(my_string[-6:]) # Output: Newbie # Grab every other character print(my_string[::2]) # Output: Hlo yhn eie
If you need to split the string by a specific separator (like commas or spaces) first, you can use the split() method, then pick the part you want:
fruits = "apple,banana,cherry" fruit_list = fruits.split(",") print(fruit_list[1]) # Output: banana
Great job getting the current time to print successfully! To get rid of those milliseconds, here are two solid methods:
Method 1: Use strftime() for formatted output (Recommended)
The datetime object has a built-in strftime() method that lets you define exactly how you want your time to look. You'll need these format codes:
%Y: 4-digit year (e.g., 2018)%m: 2-digit month (e.g., 04)%d: 2-digit day (e.g., 05)%H: 24-hour format hour (e.g., 10)%M: Minute (e.g., 55)%S: Second (e.g., 36)
Here's your modified code:
from datetime import datetime current_time = datetime.now() # Print with your desired format—no milliseconds! print(current_time.strftime("%Y-%m-%d %H:%M:%S"))
Method 2: String slicing (Quick but less reliable)
If you don't want to memorize format codes, you can convert the datetime object to a string and just take the first 19 characters (since the default output starts with YYYY-MM-DD HH:MM:SS before the milliseconds):
from datetime import datetime current_time = datetime.now() # Slice the string to keep only the first 19 characters print(str(current_time)[:19])
A quick heads-up: This depends on Python's default string format for datetime objects. If that ever changes in a future version, this method might break. So Method 1 is the safer bet long-term.
内容的提问来源于stack exchange,提问作者vikino

