【问题标题】:Print current time in Python 3在 Python 3 中打印当前时间
【发布时间】:2019-07-08 13:53:41
【问题描述】:

我在尝试在 python 上打印时间时遇到了麻烦。 这是我最近尝试的代码:

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

【问题讨论】:

  • 我的意思是,这段代码没有打印任何东西,所以你可能应该使用print函数
  • 仅供参考 - 为什么投票很重要? stackoverflow.com/help/why-vote -- 请选择并回答能解决您的问题

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    λ 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'                                                                                                   
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2012-09-13
      相关资源
      最近更新 更多