【问题标题】:Converting time.struct_time into a string using formatting使用格式化将 time.struct_time 转换为字符串
【发布时间】:2015-10-22 14:32:42
【问题描述】:

我有这种格式:

(Pdb) aa = time.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f")
(Pdb) aa
time.struct_time(tm_year=2015, tm_mon=2, tm_mday=28, tm_hour=14, tm_min=19, tm_sec=5, tm_wday=5, tm_yday=59, tm_isdst=-1)

如何将其转换为字符串'2015-02-28T14:19:05'

【问题讨论】:

    标签: python date time format


    【解决方案1】:

    一种方法是使用 time.strftime() ,示例 -

    import time
    time.strftime('%Y-%m-%dT%H:%M:%S',time.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f"))
    >> '2015-02-28T14:19:05'
    

    但是您应该考虑使用datetime 模块,它在解析/处理日期/时间方面更强大。示例 -

    import datetime
    datetime.datetime.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f").strftime('%Y-%m-%dT%H:%M:%S')
    >> '2015-02-28T14:19:05'
    

    【讨论】:

      【解决方案2】:

      您可能希望使用日期时间而不是时间。

      from datetime import datetime
      aa=datetime.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f")
      str(aa)
      

      应该给你你正在寻找的东西。

      【讨论】:

      • str(datetime.datetime.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f")) 给我 - '2015-02-28 14:19:05.512000'
      • @AnandSKumar,是的,我并没有真正尝试过代码,但我看到您还发布了解决问题的解决方案。不用我再推了。
      猜你喜欢
      • 2020-09-09
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 2022-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多