如何获取当前时间?
当前回答
最快的方法是:
>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
其他回答
从中尝试箭头模块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
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150
对于没有日期的时钟时间:
>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150
要保存键入,可以从datetime模块导入datetime对象:
>>> from datetime import datetime
然后删除前缀datetime。从以上所有方面来看。
与Harley的答案类似,但使用str()函数实现一种更快速、更易于阅读的格式:
>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
为什么不问问美国海军的官方计时员美国海军天文台?
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
如果你住在华盛顿地区(像我一样),延迟可能不会太差。。。
要在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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录