【问题标题】:how can I strip the 00:00:00 from a date in python如何从 python 中的日期中删除 00:00:00
【发布时间】:2021-12-22 14:00:47
【问题描述】:

这可能是一个非常简单的问题,但我使用下面的代码将 1 天添加到日期,然后输出新日期。我在网上找到了这段代码。

from datetime import datetime
from datetime import timedelta
  
# taking input as the date
Begindatestring = "2020-10-11"
  
# carry out conversion between string 
# to datetime object
Begindate = datetime.strptime(Begindatestring, "%Y-%m-%d")
  
# print begin date
print("Beginning date")
print(Begindate)
  
# calculating end date by adding 1 day
Enddate = Begindate + timedelta(days=1)
  
# printing end date
print("Ending date")
print(Enddate)

这段代码有效,但它给我的输出看起来像这样

Beginning date
2020-10-11 00:00:00
Ending date
2020-10-12 00:00:00

但是为了让我的其余代码正常运行,我需要摆脱 00:00:00 所以我需要一个看起来像这样的输出

    Beginning date
    2020-10-11
    Ending date
    2020-10-12

似乎有一个简单的解决方案,但我找不到。

【问题讨论】:

    标签: python date datetime time


    【解决方案1】:

    尝试使用:

    print(Begindate.strftime("%Y-%m-%d"))
    

    查看https://www.programiz.com/python-programming/datetime/strftime了解更多信息。

    【讨论】:

    • 成功了,谢谢。
    【解决方案2】:
    Begindate = datetime.strptime(Begindatestring, "%Y-%m-%d").date()
    
    Enddate = Enddate.date()
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2019-03-28
      • 1970-01-01
      • 2013-07-12
      • 2013-06-09
      • 2021-10-21
      相关资源
      最近更新 更多