如何获取当前时间?
当前回答
使用time.strftime():
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
其他回答
您可以使用此函数获取时间(遗憾的是,它没有显示AM或PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
要获取稍后要合并的小时、分钟、秒和毫秒,可以使用以下函数:
小时:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
分钟:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
第二:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
毫秒:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
示例输出:“2013-09-18 11:16:32”
请参阅strftime指令列表。
对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)
如果您将其用于django datetime有时在服务器上无法工作,所以我建议使用时区
但要使用django时区,您应该在设置中设置您的国家/地区时区代码。py
TIME_ZONE = 'Asia/Tashkent'
那你就可以用它了
from django.utils import timezone
timezone.now() // for date time
timezone.now().year // for yaer
timezone.now().month // for month
timezone.now().day // for day
timezone.now().date // for date
timezone.now().hour // for hour
timezone.now().weekday // for minute
或者如果您想在python上使用
import time
time.strftime('%X') // '13:12:47'
time.strftime('%x') // '01/20/22'
time.strftime('%d') // '20' day
time.strftime('%m') // '01' month
time.strftime('%y') // '20' year
time.strftime('%H') // '01' hour
time.strftime('%M') // '01' minute
time.strftime('%m') // '01' second
如果您需要用于计时函数调用的时间,那么您需要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