如何获取当前时间?


当前回答

使用time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

其他回答

如果您已经在使用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'))

前面的答案都是很好的建议,但我发现使用ctime()最简单:

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

这提供了当前本地时间的格式良好的字符串表示。

这很简单。尝试:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]
import datetime
import pytz # for timezone()
import time

current_time1 = datetime.datetime.now()
current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
current_time3 = datetime.datetime.utcnow()
current_time4 = datetime.datetime.now().isoformat()
current_time5 = time.gmtime(time.time())

print("datetime.datetime.now():", current_time1)
print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2)
print("datetime.utcnow():", current_time3)
print("datetime.datetime.now().isoformat():", current_time4)
print('time.gmtime(time.time()): ', current_time5)

从中尝试箭头模块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'