如何获取当前时间?
当前回答
您可以使用此函数获取时间(遗憾的是,它没有显示AM或PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
要获取稍后要合并的小时、分钟、秒和毫秒,可以使用以下函数:
小时:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
分钟:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
第二:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
毫秒:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
其他回答
您可以使用时间模块:
>>> import time
>>> print(time.strftime("%d/%m/%Y"))
06/02/2015
使用大写Y表示全年,使用Y表示2015年2月6日。
您也可以使用以下代码来延长时间:
>>> time.strftime("%a, %d %b %Y %H:%M:%S")
'Fri, 06 Feb 2015 17:45:09'
从中尝试箭头模块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'
下面是根据您的问题只显示时间的代码:
from datetime import datetime
time= datetime.now()
b = time.strftime("%H:%M:%S")
print(b)
使用datetime.now()获取当前日期和时间。然后使用.strftime获取所需值,即仅时间。
strftime用于检索所需的输出或根据需要更改默认格式。
如果您需要用于计时函数调用的时间,那么您需要time.perf_counter()。
start_time = time.perf_counter()
expensive_function()
time_taken = time.perf_counter() - start_time
print(f'expensive_function() took {round(time_taken,2)}s')
time.perf_counter()→ 浮动返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它确实包括了睡眠期间的时间,并且是系统范围内的。返回值的引用点未定义,因此只有连续调用结果之间的差异才有效。3.3版新增。time.perf_counter_ns()→ 整数与perf_counter()类似,但返回时间为纳秒。3.7版新增。
https://docs.python.org/3/library/time.html#time.perf_counter
使用熊猫来获取当前的时间,有点过分了眼前的问题:
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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录