How to get current time in Python?

什么是用于获得当前时间的模块/方法?


>>> import datetime
>>> datetime.datetime.now()
datetime(2009, 1, 6, 15, 8, 24, 78915)

And just the time:

>>> datetime.datetime.time(datetime.datetime.now())
datetime.time(15, 8, 24, 78915)

The same but slightly more compact:

>>> datetime.datetime.now().time()

See the documentation for more info.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the leading datetime. from all the above.


你可以使用time.strftime()

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

类似于Harley的回答,但是使用str()函数来获得一个快速n-dirty的,稍微更人性化的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
链接地址: http://www.djcxy.com/p/1070.html

上一篇: 在Python中获取实例的类名

下一篇: 如何在Python中获取当前时间?