## 目录

• 如何用 `datetime` 模块获取当前时间
• `datetime.now()` 函数的属性
• 如何用 `datetime` 获取某个时区的当前时间
• 总结

## 如何用 `datetime` 模块获取当前时间

``````from datetime import datetime
``````

``````from datetime import datetime
currentDateAndTime = datetime.now()

print("The current date and time is", currentDateAndTime)
# Output: The current date and time is 2022-03-19 10:05:39.482383
``````

``````from datetime import datetime
currentDateAndTime = datetime.now()

print("The current date and time is", currentDateAndTime)
# Output: The current date and time is 2022-03-19 10:05:39.482383

currentTime = currentDateAndTime.strftime("%H:%M:%S")
print("The current time is", currentTime)
# The current time is 10:06:55
``````

## `datetime.now()` 函数的属性

`datetime.now` 函数有几个属性，你可以通过它们获得当前日期的年、月、周、日、小时、分钟和秒。

``````from datetime import datetime
currentDateAndTime = datetime.now()

print("The current year is ", currentDateAndTime.year) # Output: The current year is  2022
print("The current month is ", currentDateAndTime.month) # Output: The current month is  3
print("The current day is ", currentDateAndTime.day) # Output: The current day is  19
print("The current hour is ", currentDateAndTime.hour) # Output: The current hour is  10
print("The current minute is ", currentDateAndTime.minute) # Output: The current minute is  49
print("The current second is ", currentDateAndTime.second) # Output: The current second is  18

``````

## 如何用 `datetime` 获取一个时区的当前时间

`pip install pytz`

``````from datetime import datetime
import pytz
``````

``````from datetime import datetime
import pytz

zones = pytz.all_timezones

print(zones)
# Output: all timezones of the world. Massive!
``````

``````from datetime import datetime
import pytz

newYorkTz = pytz.timezone("America/New_York")
timeInNewYork = datetime.now(newYorkTz)
currentTimeInNewYork = timeInNewYork.strftime("%H:%M:%S")

print("The current time in New York is:", currentTimeInNewYork)
# Output: The current time in New York is: 05:36:59
``````