如何获取当前时间?


当前回答

这应该行得通

import time

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("The current time is", current_time)

其他回答

import datetime
date_time = datetime.datetime.now()

date = date_time.date()  # Gives the date
time = date_time.time()  # Gives the time

print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond

执行dir(date)或包括包在内的任何变量。您可以获取与变量关联的所有属性和方法。

时间模块可以导入各种时间信息,包括睡眠和其他类型的信息,包括当前时间类型

import time
time.strftime("%T", time.localtime())

输出应如下所示

05:46:33
11:22:56
13:44:55
22:33:44
00:00:00

获取当前日期时间属性:

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

您可以尝试以下操作

import datetime

now = datetime.datetime.now()
print(now)

or

import datetime

now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date将打印日期,time将打印时间。