python 3.5.0 :::打印日期和时间

时间:2015-11-05 19:02:26

标签: python date datetime time

所以我使用datetime模块来打印日期,并且到目前为止。

但是我无法打印时间......

每次我跑:

currentTime = datetime.time()
print (currentTime) 

结果是:

00:00:00

我试过了:

print(datetime.datetime.now())
>>>> 05-11-2015 19:00.173546

但我只想要时间:19:00

你知道怎么做吗?那是否有功能?

3 个答案:

答案 0 :(得分:2)

datetime.time()相当于datetime.time(hours=0, minute=0)

>>> import datetime
>>> datetime.time()
datetime.time(0, 0)
>>> datetime.time(hour=0, minute=0)
datetime.time(0, 0)

datetime是一个模块。 datetime.time是一个班级。 datetime.time()是使用默认小时,分钟值(00)创建的该类的实例,例如,创建与19:00对应的time对象相反,您可以使用datetime.time(19, 0)

要仅打印现有datettime.datetimedatetime.time个实例的时间,您可以使用%H:%M time format

>>> import datetime
>>> current_time = datetime.datetime.now()
>>> print("{:%H:%M}".format(current_time))
08:40

答案 1 :(得分:0)

date_time = datetime.datetime.now()
time = date_time.time()

# date_time is a datetime object tuple of year, month, day, hour, minnute, second, ms 
# to access the time portion, simply call the time() function, which will return a tuple of only the hour, minue, second portion

# printing the time will give timestamp representation, but the object is actually of type datetime.time

答案 2 :(得分:0)

像这样:

from datetime import datetime;

t = datetime.now();
print '%d-%d' % (t.hour, t.minute);
#prints 19:17