如何获取当前时间?
当前回答
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)
其他回答
Do
from time import time
t = time()
t-浮点数,适用于时间间隔测量。
Unix和Windows平台有一些不同。
要在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)
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'
以指定格式输出当前GMT。还有一个localtime()方法。
此页包含更多详细信息。
.iformat()在文档中,但这里还没有(这与@Ray Vega的回答非常相似):
>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
对UTC日期时间、本地日期时间使用此方法,并转换上午和下午
import pytz
from datetime import datetime
#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)
#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)
#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录