如何获取当前时间?
当前回答
要在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)
其他回答
如果需要当前时间作为时间对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
获取当前日期时间属性:
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
我们可以使用datetime模块来完成
>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54
此外,我们可以使用pytZ模块获取当前时间zome。
>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31
使用time.strftime():
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
使用熊猫来获取当前的时间,有点过分了眼前的问题:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
输出:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693