如何获取当前时间?


当前回答

如果您需要用于计时函数调用的时间,那么您需要time.perf_counter()。

start_time = time.perf_counter()
expensive_function()
time_taken = time.perf_counter() - start_time
print(f'expensive_function() took {round(time_taken,2)}s')

time.perf_counter()→ 浮动返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它确实包括了睡眠期间的时间,并且是系统范围内的。返回值的引用点未定义,因此只有连续调用结果之间的差异才有效。3.3版新增。time.perf_counter_ns()→ 整数与perf_counter()类似,但返回时间为纳秒。3.7版新增。

https://docs.python.org/3/library/time.html#time.perf_counter

其他回答

首先从datetime导入datetime模块

from datetime import datetime

然后将当前时间打印为“yyyy-mm-dd hh:mm:ss”

print(str(datetime.now())

要只获取形式为“hh:mm:ss”的时间,其中ss代表完整的秒数加上所用的秒数,只需执行以下操作即可;

print(str(datetime.now()[11:])

将datetime.now()转换为字符串,得到的答案格式与我们习惯的常规DATES AND TIMES格式相似。

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

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

使用日期时间:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150

对于没有日期的时钟时间:

>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150

要保存键入,可以从datetime模块导入datetime对象:

>>> from datetime import datetime

然后删除前缀datetime。从以上所有方面来看。