如何获取当前时间?
当前回答
这应该行得通
import time
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("The current time is", current_time)
其他回答
如果需要当前时间作为时间对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
与Harley的答案类似,但使用str()函数实现一种更快速、更易于阅读的格式:
>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
datetime.now()将当前时间作为一个天真的datetime对象返回,该对象表示本地时区中的时间。该值可能不明确,例如,在DST过渡期间(“回落”)。为避免歧义,应使用UTC时区:
from datetime import datetime
utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417
或者一个带有相应时区信息的时区感知对象(Python 3.2+):
from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
now()的属性可用于获取python中的当前时间:
# 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)
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
执行dir(date)或包括包在内的任何变量。您可以获取与变量关联的所有属性和方法。