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:40

By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file getDateTime1.py with the below content.

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624
查看更多
梦该遗忘
3楼-- · 2018-12-31 23:40

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the "timeit" module:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))
查看更多
旧时光的记忆
4楼-- · 2018-12-31 23:42
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.

查看更多
泛滥B
5楼-- · 2018-12-31 23:42
import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]

date will print date and time will print time.

查看更多
余生无你
6楼-- · 2018-12-31 23:45

This is what I ended up going with:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).

strftime format code table

查看更多
泛滥B
7楼-- · 2018-12-31 23:46
>>> from datetime import datetime
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')

For this example, the output will be like this: '2013-09-18 11:16:32'

Here is the list of strftime.

查看更多
登录 后发表回答