【问题标题】:Format time string in Python 3.3在 Python 3.3 中格式化时间字符串
【发布时间】:2014-03-04 07:26:38
【问题描述】:

我正在尝试以字符串形式获取当前本地时间,格式为:年-月-日时:分:秒。我将用于记录。通过阅读文档,我可以通过以下方式做到这一点:

import time
'{0:%Y-%m-%d %H:%M:%S}'.format(time.localtime())

但是我得到了错误:

回溯(最近一次通话最后): 文件“”,第 1 行,在 ValueError:格式说明符无效

我做错了什么?有没有更好的办法?

【问题讨论】:

    标签: python python-3.x datetime python-3.3


    【解决方案1】:

    time.localtime 返回不支持 strftime 格式的 time.struct_time

    传递支持 strftime 格式的 datetime.datetime 对象。 (见datetime.datetime.__format__

    >>> import datetime
    >>> '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
    '2014-02-07 11:52:21'
    

    【讨论】:

    • 使用 datetime.datetime 代替时间有什么缺点吗?
    • 好的,我看到这里有区别:stackoverflow.com/questions/7479777/…,datetime 更适合我的需要,谢谢!
    • 也试试这个:f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}"
    • @Kieveli,问题被标记为python-3.3。 f-string 语法在 Python 3.6+ 中可用。 Another answer 已经提到了 f-string。 :)
    【解决方案2】:

    对于较新版本的 Python(3.6+,https://www.python.org/dev/peps/pep-0498/ 纯粹是为了完整性),您可以使用较新的字符串格式,即。

    import datetime
    
    today = datetime.date.today()
    
    f'{today:%Y-%m-%d}'
    > '2018-11-01'
    

    【讨论】:

      【解决方案3】:

      您也可以使用time.strftime:

      time.strftime('{%Y-%m-%d %H:%M:%S}')
      

      【讨论】:

      • 我很确定0: 对于strftime 来说是多余的。 +1
      猜你喜欢
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2019-11-28
      相关资源
      最近更新 更多