如何获取当前时间?


当前回答

import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date将打印日期,time将打印时间。

其他回答

与Harley的答案类似,但使用str()函数实现一种更快速、更易于阅读的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

默认情况下,now()函数以YYYY-MM-DD HH:MM:SS:MS格式返回输出。使用以下示例脚本获取Python脚本中的当前日期和时间,并在屏幕上打印结果。使用以下内容创建文件getDateTime1.py。

import datetime

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

输出如下所示:

2018-03-01 17:03:46.759624

Do

from time import time

t = time()

t-浮点数,适用于时间间隔测量。

Unix和Windows平台有一些不同。

这个问题不需要一个新的答案。。。然而,一个闪亮的新玩具/模块就足够了。这就是摆库,它似乎做了箭头所尝试的那种事情,除了没有困扰箭头的固有缺陷和缺陷。

例如,原始问题的答案:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

有很多标准需要解决,包括多个RFC和ISO。曾经把它们混在一起;不用担心,稍微了解一下dir(钟摆常量),但这里有一点不仅仅是RFC和ISO格式。

当我们说本地时,我们是什么意思?我的意思是:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

想必你们中的大多数人都是指其他地方。

然后继续。长话短说:Pendulum试图在日期和时间上做HTTP请求所做的事情。它值得考虑,特别是它的易用性和广泛的文档。

import datetime
import pytz # for timezone()
import time

current_time1 = datetime.datetime.now()
current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
current_time3 = datetime.datetime.utcnow()
current_time4 = datetime.datetime.now().isoformat()
current_time5 = time.gmtime(time.time())

print("datetime.datetime.now():", current_time1)
print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2)
print("datetime.utcnow():", current_time3)
print("datetime.datetime.now().isoformat():", current_time4)
print('time.gmtime(time.time()): ', current_time5)