原文:How to Get the Current Time in Python with Datetime,作者:Kolade Chris
在你的 Python 应用程序中,你可能想设置时间,以增加诸如时间戳的功能,检查用户活动的时间,等等。
在 Python 中帮助你处理日期和时间的模块之一是 datetime
。
使用 datetime
模块,你可以得到当前的日期和时间,或者某个特定时区的当前日期和时间。
在这篇文章中,我将向你展示如何在 Python 中用 datetime
模块获得当前时间。我还将告诉你如何获得世界上任何一个时区的当前时间。
目录
- 如何用
datetime
模块获取当前时间 datetime.now()
函数的属性- 如何用
datetime
获取某个时区的当前时间 - 总结
如何用 datetime
模块获取当前时间
你首先要做的是像这样导入 datetime
模块。
from datetime import datetime
接下来你可以做的是使用 datetime
模块中的 datetime.now()
函数来快速获得当前日期和时间。
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
要获得当前时间,你可以使用 strftime()
方法,并向其传递代表小时、分钟和秒的字符串 ”%H:%M:%S”
。
这将给你提供 24 小时格式的当前时间。
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
获取一个时区的当前时间
你可以通过使用 datetime
模块和另一个叫 pytz
的模块来获得某个特定时区的当前时间。
你可以像这样从 pip 中安装 pytz
模块:pip install pytz
首先你需要导入 datetime
和 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
我是如何获得纽约的当前时间的呢?
我引入了 pytz
模块的 pytztimezone()
方法,将纽约的确切时区作为一个字符串传入其中,并将其分配给一个名为 newYorkTz
的变量(代表纽约时区)。
为了获得纽约的当前时间,我使用了 datetime
模块中的 datetime.now()
函数,并将我创建的用于存储纽约时区的变量传入其中。
为了最终得到 24 小时格式的纽约当前时间,我对 timeInNewYork
变量使用了 strftime()
方法,并将其存储在一个名为 currentTimeInNewYork
的变量中,这样我就可以将其打印到终端。
总结
如本文所示,datetime
模块在处理时间和日期方面非常方便,随后可以得到你所在地区的当前时间。
当与你可以从 pip 安装的 pytz
模块结合时,你也可以用它来获得世界上任何一个时区的当前时间。
谢谢你阅读本文。如果你觉得这篇文章对你有帮助,你可以与朋友和家人分享它。