如何获取当前时间?


当前回答

获取当前日期时间属性:

import datetime

currentDT = datetime.datetime.now()

print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)


#!/usr/bin/python
import time;

ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks

其他回答

下面是根据您的问题只显示时间的代码:

 from datetime import datetime
 time= datetime.now()
 b = time.strftime("%H:%M:%S")
 print(b)

使用datetime.now()获取当前日期和时间。然后使用.strftime获取所需值,即仅时间。

strftime用于检索所需的输出或根据需要更改默认格式。

如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“timeit”模块:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

示例输出:“2013-09-18 11:16:32”

请参阅strftime指令列表。

这很简单。尝试:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]

我们可以使用datetime模块来完成

>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54

此外,我们可以使用pytZ模块获取当前时间zome。

>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31