在Python 3中打印当前时间

时间:2019-02-14 13:54:30

标签: python python-3.x datetime time console

我无法在python上打印时间。 这是我最近尝试过的代码:

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

2 个答案:

答案 0 :(得分:0)

出什么问题了?您的代码有效

λ python                                                                                                     
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32         
Type "help", "copyright", "credits" or "license" for more information.                                       
>>> from time import gmtime, strftime   

>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())                                                                  
'2019-02-14 13:56:02'                                                                                        

>>> strftime("%H:%M:%S", gmtime())                                                                           
'13:56:16'                                                                                                   
>>>          

编辑:

此代码在终端中可以正常工作-如@ForceBru所述,如果您在脚本中运行它,则需要使用打印功能来显示strftime

的结果
from time import gmtime, strftime   

print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))                                                                 
> '2019-02-14 13:56:02'                                                                                        

print(strftime("%H:%M:%S", gmtime()))  
> '13:56:16'                                                                                                   

答案 1 :(得分:0)

您的原始代码是正确的,但缺少打印语句。

from time import gmtime, strftime
print (strftime("%Y-%m-%d %H:%M:%S", gmtime()))
# output
2019-02-14 14:56:18

还有其他一些方法可以获取协调世界时(UTC)/格林威治标准时间(GMT)时间戳。

from datetime import datetime
from datetime import timezone

current_GMT_timestamp = datetime.utcnow()
print (current_GMT_timestamp)
# output
2019-02-14 14:56:18.827431

# milliseconds removed from GMT timestamp
reformatted_GMT_timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
print (reformatted_GMT_timestamp)
# output
2019-02-14 14:56:18

# GMT in ISO Format
current_ISO_GMT_timestamp = datetime.now(timezone.utc).isoformat()
print (current_ISO_GMT_timestamp)
# output
2019-02-14T14:56:18.827431+00:00