如何获取当前时间?
当前回答
与Harley的答案类似,但使用str()函数实现一种更快速、更易于阅读的格式:
>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
其他回答
获取当前日期时间属性:
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
如果您已经在使用numpy,那么可以直接使用numpy.datetime64()作用
import numpy as np
str(np.datetime64('now'))
仅限日期:
str(np.datetime64('today'))
或者,如果您已经在使用pandas,则可以使用pandas.to_datetime()函数
import pandas as pd
str(pd.to_datetime('now'))
or,
str(pd.to_datetime('today'))
如果需要当前时间作为时间对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time
date将打印日期,time将打印时间。
时间模块可以导入各种时间信息,包括睡眠和其他类型的信息,包括当前时间类型
import time
time.strftime("%T", time.localtime())
输出应如下所示
05:46:33
11:22:56
13:44:55
22:33:44
00:00:00
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录