【问题标题】:How to split current date time and retrieve only date , hour and minute? [duplicate]如何拆分当前日期时间并仅检索日期、小时和分钟? [复制]
【发布时间】:2021-06-06 23:41:10
【问题描述】:
current_time = datetime.datetime.now()
print("current time ", current_time)

结果:

current time  2021-03-08 23:22:59.912410

在这里,我只想要分钟(2021-03-08 23:22)并且需要从当前时间去除秒和毫秒。 请帮忙

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用strftime() 以特定格式输出日期,即:

    import datetime
    
    current_time = datetime.datetime.now()
    print("current time ", current_time.strftime("%Y-%m-%d %H:%M:%S"))
    # current time 2021-03-09 04:42:57
    

    Demo

    【讨论】:

    • 打败我。 @TechG,here 是 Pedro 在 Python 文档中使用的符号 (%Y-%m-%d %H:%M:%S) 的表格。
    【解决方案2】:

    您必须根据您想要的格式重新格式化字符串中的时间。

    formatted = current_time.strftime("%Y-%m-%d %H:%M:%S")
    print(formatted)
    

    输出如下:

    '2021-03-09 10:12:58'
    

    它还将datetime 对象更改为str。因此无法对其执行datetime 操作。建议仅用于输出演示。

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多