如何获取当前时间?


当前回答

试试这个:-

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_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]

时区的当前时间

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

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

这就是我最终要做的:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

此外,该表是选择适当格式代码以按照您想要的方式格式化日期的必要参考(来自Python“datetime”文档)。