杰瑞科技汇

python datetime.now

Of course! The datetime.now() function is one of the most commonly used tools in Python for working with dates and times. Here’s a comprehensive guide covering everything from the basics to more advanced usage.

python datetime.now-图1
(图片来源网络,侵删)

The Basics: Getting the Current Date and Time

To use datetime.now(), you first need to import the datetime class from the datetime module.

from datetime import datetime
# Get the current local date and time
now = datetime.now()
# Print the result
print(now)

Example Output:

2025-10-27 10:30:55.123456

This output is a datetime object that contains:

  • Date: Year, Month, Day
  • Time: Hour, Minute, Second, Microsecond

Getting Only the Current Date or Time

Often, you don't need both the date and the time. The datetime object has convenient methods to get just one part.

python datetime.now-图2
(图片来源网络,侵删)

Getting the Current Date

Use the .date() method to get a date object.

from datetime import datetime
now = datetime.now()
current_date = now.date()
print(f"Full datetime object: {now}")
print(f"Current date only: {current_date}")

Example Output:

Full datetime object: 2025-10-27 10:30:55.123456
Current date only: 2025-10-27

Getting the Current Time

Use the .time() method to get a time object.

from datetime import datetime
now = datetime.now()
current_time = now.time()
print(f"Full datetime object: {now}")
print(f"Current time only: {current_time}")

Example Output:

python datetime.now-图3
(图片来源网络,侵删)
Full datetime object: 2025-10-27 10:30:55.123456
Current time only: 10:30:55.123456

datetime.now() vs. datetime.utcnow()

There's a crucial difference between now() and utcnow().

  • datetime.now(): Returns the current local date and time, including timezone information (if the system is configured correctly).
  • datetime.utcnow(): Returns the current UTC (Coordinated Universal Time) date and time, without any timezone information.

Why does this matter? Working with timezone-aware datetimes is highly recommended to avoid bugs, especially when dealing with servers or users in different timezones.

Example: The Difference

from datetime import datetime
# Local time (usually timezone-aware on modern systems)
local_now = datetime.now()
print(f"Local Now: {local_now}")
print(f"Timezone Info: {local_now.tzinfo}") # Will be None if not set
# UTC time (always naive, no timezone info)
utc_now = datetime.utcnow()
print(f"\nUTC Now: {utc_now}")
print(f"Timezone Info: {utc_now.tzinfo}") # This will always be None

Example Output (on a machine in New York, USA):

Local Now: 2025-10-27 10:30:55.123456-04:00
Timezone Info: UTC-04:00 (or similar)
UTC Now: 2025-10-27 14:30:55.123456
Timezone Info: None

Notice how the UTC time is 4 hours ahead of the local time (because it's Eastern Daylight Time, UTC-4). The key takeaway is that utcnow() creates a "naive" object, which can lead to confusion.


Best Practice: Using Timezone-Aware Datetimes

For robust applications, you should always use timezone-aware datetimes. The zoneinfo module (standard in Python 3.9+) is the modern way to do this.

from datetime import datetime
from zoneinfo import ZoneInfo # Requires Python 3.9+
# Get the current time in a specific timezone
ny_tz = ZoneInfo("America/New_York")
tokyo_tz = ZoneInfo("Asia/Tokyo")
# Use the 'tz' argument to make the datetime object timezone-aware
now_in_ny = datetime.now(tz=ny_tz)
now_in_tokyo = datetime.now(tz=tokyo_z)
print(f"Time in New York: {now_in_ny}")
print(f"Time in Tokyo: {now_in_tokyo}")
print(f"Timezone Info for NY: {now_in_ny.tzinfo}")

Example Output:

Time in New York: 2025-10-27 10:30:55.123456-04:00
Time in Tokyo: 2025-10-27 27 10:30:55.123456+09:00
Timezone Info for NY: America/New_York

Formatting Datetime Objects for Display

The default string representation isn't always user-friendly. You can format it into any string you like using the .strftime() method (String Format Time).

Code Meaning Example
%Y Year with century 2025
%m Month as a zero-padded number 10
%B Full month name October
%d Day of the month as a zero-padded number 27
%H Hour (24-hour clock) 10
%I Hour (12-hour clock) 10
%M Minute 30
%S Second 55
%p AM or PM AM
%A Full weekday name Friday
from datetime import datetime
now = datetime.now()
# Format 1: YYYY-MM-DD
format1 = now.strftime("%Y-%m-%d")
print(f"Format 1: {format1}") # e.g., 2025-10-27
# Format 2: MM/DD/YYYY
format2 = now.strftime("%m/%d/%Y")
print(f"Format 2: {format2}") # e.g., 10/27/2025
# Format 3: Day, Month Day, Year
format3 = now.strftime("%A, %B %d, %Y")
print(f"Format 3: {format3}") # e.g., Friday, October 27, 2025
# Format 4: HH:MM:SS (24-hour clock)
format4 = now.strftime("%H:%M:%S")
print(f"Format 4: {format4}") # e.g., 10:30:55

Creating a datetime Object from a String

The reverse of formatting is parsing. You can use datetime.strptime() (String Parse Time) to create a datetime object from a string.

from datetime import datetime
date_string = "2025-10-27 10:30:00"
# The format code must match the string exactly
dt_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Original string: {date_string}")
print(f"Parsed datetime object: {dt_object}")
print(f"Type of object: {type(dt_object)}")

Example Output:

Original string: 2025-10-27 10:30:00
Parsed datetime object: 2025-10-27 10:30:00
Type of object: <class 'datetime.datetime'>

Summary: Key Takeaways

Task Method / Code Example
Get current local time datetime.now() now = datetime.now()
Get current date only .date() today = now.date()
Get current time only .time() time_now = now.time()
Get current UTC time datetime.utcnow() utc_now = datetime.utcnow()
Get timezone-aware time datetime.now(tz=...) ny_time = datetime.now(tz=ZoneInfo("America/New_York"))
Format datetime to string .strftime() now.strftime("%Y-%m-%d")
Parse string to datetime datetime.strptime() datetime.strptime("2025-10-27", "%Y-%m-%d")
分享:
扫描分享到社交APP
上一篇
下一篇