如何获取当前时间?


当前回答

对UTC日期时间、本地日期时间使用此方法,并转换上午和下午

import pytz
from datetime import datetime

#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)

#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)

其他回答

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

要在11:34:23.751毫秒内精确获得3个小数点,请运行以下命令:

def get_time_str(decimal_points=3):
        return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

更多上下文:

我想用毫秒来计算时间。获取它们的简单方法:

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

但我只需要几毫秒,对吧?获取它们的最短方法:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

在最后一次乘法中添加或删除零以调整小数点的数量,或仅执行以下操作:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

首先从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格式相似。

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

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