How to get the current time in Python

2018-12-31 23:16发布

What is the module/method used to get the current time?

30条回答
人气声优
2楼-- · 2018-12-31 23:19

Do

from time import time

t = time()
  • t - float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.

查看更多
大哥的爱人
3楼-- · 2018-12-31 23:19

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
查看更多
只若初见
4楼-- · 2018-12-31 23:20

Similar to Harley's answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
查看更多
怪性笑人.
5楼-- · 2018-12-31 23:21

Simple and easy:

Using the datetime module,

import datetime
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

Output:

2017-10-17 23:48:55

OR

Using time,

import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))

Output:

2017-10-17 18:22:26
查看更多
其实,你不懂
6楼-- · 2018-12-31 23:23

Use:

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

>>> print(datetime.datetime.now())
2018-07-29 09:17:13.812189

And just the time:

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

>>> print(datetime.datetime.now().time())
09:17:51.914526

See the documentation for more information.

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

>>> from datetime import datetime

Then remove the leading datetime. from all of the above.

查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 23:23

You can use the time module.

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use to give a more lengthy time.

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'
查看更多
登录 后发表回答