使用Python获取当前日期和时间
先决条件:日期时间模块
在这个例子中,我们将学习如何使用Python获取当前日期和时间。
在Python中,日期和时间不是它自己的数据类型,但是可以导入一个名为datetime
的模块来处理日期和时间。 Datetime 模块内置于Python中,因此无需外部安装。
要获取当前日期和时间,请使用datetime
模块的datetime.now()
函数。此函数返回当前的本地日期和时间。
Syntax : datetime.now(tz)
Parameters :
tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Returns : Returns the current date and time in time format.
示例 1:
# Python3 code to demonstrate
# Getting current date and time using
# now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print ("Time now at greenwich meridian is : "
, end = "")
print (current_time)
输出:
Time now at greenwich meridian is : 2019-12-11 13:54:30.967356
now() 的属性:
now()
具有不同的属性,与时间的属性相同,例如年、月、日、小时、分钟、秒。
示例 2:
# Python3 code to demonstrate
# attributes of now()
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing attributes of now().
print ("The attributes of now() are : ")
print ("Year : ", end = "")
print (current_time.year)
print ("Month : ", end = "")
print (current_time.month)
print ("Day : ", end = "")
print (current_time.day)
print ("Hour : ", end = "")
print (current_time.hour)
print ("Minute : ", end = "")
print (current_time.minute)
print ("Second : ", end = "")
print (current_time.second)
print ("Microsecond : ", end = "")
print (current_time.microsecond)
输出:
The attributes of now() are :
Year : 2019
Month : 12
Day : 11
Hour : 13
Minute : 56
Second : 7
Microsecond : 292616
获取特定时区的时间:
在上面的例子中,可以看出上面的代码没有给出你所在时区的当前日期和时间。要获取特定时区的日期和时间, now()
将时区作为输入,以提供面向时区的输出时间。但是这些时区是在pytz库中定义的。
示例:3
# Python3 code to demonstrate
# attributes of now() for timezone
# for now()
import datetime
# for timezone()
import pytz
# using now() to get current time
current_time = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
# printing current time in india
print ("The current time in india is : ")
print (current_time)
输出:
The current time in india is :
2019-12-11 19:28:23.973616+05:30