如何获取当前时间?


当前回答

时区的当前时间

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

其他回答

>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'

如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“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))

我们可以使用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

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

如果需要当前时间作为时间对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)