如何获取当前时间?


当前回答

import datetime

todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12

# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38

其他回答

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

获取当前日期时间属性:

import datetime

currentDT = datetime.datetime.now()

print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)


#!/usr/bin/python
import time;

ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks

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

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

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

如果需要当前时间作为时间对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

datetime.now()将当前时间作为一个天真的datetime对象返回,该对象表示本地时区中的时间。该值可能不明确,例如,在DST过渡期间(“回落”)。为避免歧义,应使用UTC时区:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

或者一个带有相应时区信息的时区感知对象(Python 3.2+):

from datetime import datetime, timezone

now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00