如何获取当前时间?


当前回答

我们可以使用datetime模块来完成

>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54

此外,我们可以使用pytZ模块获取当前时间zome。

>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31

其他回答

使用日期时间:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150

对于没有日期的时钟时间:

>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150

要保存键入,可以从datetime模块导入datetime对象:

>>> from datetime import datetime

然后删除前缀datetime。从以上所有方面来看。

如果你经常使用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'

要在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)

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

我们可以使用datetime模块来完成

>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54

此外,我们可以使用pytZ模块获取当前时间zome。

>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31