如何获取当前时间?


当前回答

使用熊猫来获取当前的时间,有点过分了眼前的问题:

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

输出:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

其他回答

Do

from time import time

t = time()

t-浮点数,适用于时间间隔测量。

Unix和Windows平台有一些不同。

如果您将其用于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

如果你经常使用panda,你可以使用Timestamp,它相当于Python的Datetime:

In [1]: import pandas as pd

In [2]: pd.Timestamp.now()
Out[2]: Timestamp('2022-06-21 21:52:50.568788')

只是时间:

In [3]: pd.Timestamp.now().strftime("%H:%M:%S")
Out[3]: '21:53:01'
import datetime

print('date='+datetime.datetime.now().__str__().split(' ')[0]+' '+'time='+datetime.datetime.now().__str__().split(' ')[1]

由于Qt被广泛使用,

from PyQt5 import QDateTime
print(QDateTime.currentDateTime().__str__().split('(')[1].rstrip(')'))