获取Python中的当前时间

Python提供了datetime模块来处理日期和时间信息。这个模块提供了很多不同的方法,其中一个是获取当前时间。在本教程中,我们将学习如何用Python获取当前时间。

null

使用datetime.now()方法获取当前时间

获取当前时间的最常用方法是使用datetime模块中的now()方法。首先,我们将导入datetime模块,然后调用now()方法。它将返回包含当前时间信息的time对象。

from datetime import datetime#Get current timenow = datetime.now()#Print current timeprint("Current Time is: ",now)#Format current time print("Current Time is: ",now.strftime("%H:%M:%S"))

输出如下所示,第一次打印将打印完整的日期和时间,包括年、月、日、时、分、秒信息。第二次打印将使用 strftime() “的方法” %%H:%%M:%%S “格式。

Current Time is: 2020-11-28 11:12:01.561611Current Time is: 11:12:01

使用Time.localtime()方法获取当前时间

Python还提供了一个名为 时间 这也提供了 本地时间() 方法,将当前localtime信息作为localtime对象返回。

import time
#Get current time
now = time.localtime()
#Print current time
print("Current Time is: ",now)

#Format current time 
print("Current Time is: ",time.strftime("%H:%M:%S",now))

输出如下。localtime()可以用print()方法打印,该方法将打印 结构时间 对象并提供如下参数形式的时间。strftime()方法可以通过time模块调用,现在应该提供如下所示的当前时间对象 time.strftime(“%%H:%%M:%%S”,现在) .

Current Time is: time.struct_time(tm_year=2020, tm_mon=11, tm_mday=28, tm_hour=11, tm_min=16, tm_sec=57, tm_wday=5, tm_yday=333, tm_isdst=0)Current Time is: 11:16:57

获取指定时区的当前时间

pytz是第三方Python模块,它使用Olson tz或时区数据来返回指定时区的时间。当前时间可以通过pytz timezone方法返回,并使用datetime.now()方法作为参数提供给timzone对象。

from datetime import datetimeimport pytztz_istanbul = pytz.timezone("Europe/Istanbul")now = datetime.now(tz_istanbul)print("Istanbul Time:",now.strftime("%H:%M:%S"))

更改当前时间格式

正如我们在前面的示例中看到的,可以使用strftime()方法更改当前时间的格式。此方法由datetime模块或time对象提供。使用time object strftime()方法更简单。格式应以字符串形式提供,如“%%H:%%M:%%S”。

from datetime import datetime

#Get current time
now = datetime.now()


#Format current time 
print("Current Time is: ",now.strftime("%H:%M:%S"))print("Current Time is: ",now.strftime("%H:%M"))print("Current Time is: ",now.strftime("%H-%M-%S"))print("Current Time is: ",now.strftime("%H-%M"))

输出如下。

Current Time is: 11:32:16Current Time is: 11:32Current Time is: 11-32-16Current Time is: 11-32
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享