如何获取当前时间?


当前回答

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

其他回答

获取当前时间并将其转换为字符串:

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

如果您已经在使用numpy,那么可以直接使用numpy.datetime64()作用

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用pandas,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))

首先从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)

从中尝试箭头模块http://crsmithdev.com/arrow/:

import arrow
arrow.now()

或UTC版本:

arrow.utcnow()

要更改其输出,请添加.format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

对于特定时区:

arrow.now('US/Pacific')

一小时前:

arrow.utcnow().replace(hours=-1)

或者如果你想要要点。

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'