杰瑞科技汇

Python当前时间怎么获取?

Of course! In Python, there are two primary ways to get the current time, depending on whether you need the date and time together or just the time.

Here’s a complete guide, starting with the most common and recommended method.


The Best Way: Using the datetime Module

The datetime module is the standard, most flexible, and recommended way to handle dates and times in Python. It provides a datetime class that represents both date and time.

Getting the Current Date and Time

To get the current local date and time, you use datetime.now().

from datetime import datetime
# Get the current date and time
now = datetime.now()
# Print the full object
print(now)
# Example Output: 2025-10-27 15:30:55.123456
# You can access individual components
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"Second: {now.second}")
print(f"Microsecond: {now.microsecond}")

Formatting the Output (Creating a String)

Often, you'll want to display the time in a specific format (e.g., MM/DD/YYYY or HH:MM:SS). You do this with the .strftime() method (string format time).

Format Code Meaning Example
%Y Year with century 2025
%y Year without century 23
%m Month as a number (01-12) 10
%B Full month name October
%b Abbreviated month name Oct
%d Day of the month (01-31) 27
%H Hour (24-hour clock) 15
%I Hour (12-hour clock) 03
%M Minute (00-59) 30
%S Second (00-59) 55
%p AM or PM PM
%A Full weekday name Friday
%f Microsecond 123456

Examples:

from datetime import datetime
now = datetime.now()
# Common format: MM/DD/YYYY
format1 = now.strftime("%m/%d/%Y")
print(f"Format 1: {format1}")
# Example Output: Format 1: 10/27/2025
# ISO 8601 format (good for sorting)
format2 = now.strftime("%Y-%m-%dT%H:%M:%S")
print(f"Format 2: {format2}")
# Example Output: Format 2: 2025-10-27T15:30:55
# Human-readable format
format3 = now.strftime("%B %d, %Y at %I:%M %p")
print(f"Format 3: {format3}")
# Example Output: Format 3: October 27, 2025 at 03:30 PM

Getting Only the Current Time

If you don't need the date, it's more efficient to use the time module. It provides a time class specifically for time of day.

from time import time
# Get the current time (without date)
current_time = time()
# This returns a floating-point number of seconds since the "epoch"
# (January 1, 1970, 00:00:00 UTC). It's not very user-friendly on its own.
print(current_time)
# Example Output: 1698388255.123456
# To format it, you still use the .strftime() method, but you must create
# a time object first.
from time import localtime
# Get the time in a struct_time object
time_struct = localtime()
# Format the struct_time object
formatted_time = time_struct.strftime("%H:%M:%S")
print(f"Formatted Time: {formatted_time}")
# Example Output: Formatted Time: 15:30:55

Summary: Which One Should You Use?

Your Goal Recommended Module Example Code
Get both date and time datetime from datetime import datetime; now = datetime.now()
Get only the time time from time import time; t = time()
Get only the date datetime from datetime import date; today = date.today()
Perform calculations with dates/times datetime from datetime import timedelta; tomorrow = now + timedelta(days=1)
Get the current time in UTC datetime from datetime import datetime; utc_now = datetime.utcnow()

Quick Reference Cheat Sheet

# Import the necessary modules
from datetime import datetime, date, time, timedelta
import time
# 1. Get current date and time (most common)
now = datetime.now()
print(f"Full Date & Time: {now}")
# 2. Get current date only
today = date.today()
print(f"Date Only: {today}")
# 3. Get current time only
current_time_obj = time(now.hour, now.minute, now.second)
print(f"Time Only: {current_time_obj}")
# 4. Format the current time
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted (YYYY-MM-DD HH:MM:SS): {formatted_date}")
# 5. Get time since epoch (useful for system-level timing)
timestamp = time.time()
print(f"Timestamp (seconds since epoch): {timestamp}")
# 6. Get current time in UTC
utc_now = datetime.utcnow()
print(f"UTC Time: {utc_now}")
# 7. Perform time calculations (e.g., add 10 days)
future_date = now + timedelta(days=10)
print(f"Date in 10 days: {future_date}")
分享:
扫描分享到社交APP
上一篇
下一篇