如何获取当前时间?


当前回答

import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date将打印日期,time将打印时间。

其他回答

试试这个:-

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

如果您需要用于计时函数调用的时间,那么您需要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

使用time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

这里有很多复杂的解决方案,初学者可能会感到困惑。我发现这是这个问题最简单的解决方案,因为它只返回所问的当前时间(没有虚饰):

import datetime

time = datetime.datetime.now()

display_time = time.strftime("%H:%M")
print(display_time)

如果您希望返回比当前时间更详细的信息,可以按照其他人的建议进行操作:

import datetime

time = datetime.datetime.now()
print(time)

虽然这种方法写起来更短,但它也会返回当前日期和毫秒,这在简单地返回当前时间时可能不需要。

如果您已经在使用numpy,那么可以直接使用numpy.datetime64()作用

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用pandas,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))