Skip to content
Advertisement

how can I strip the 00:00:00 from a date in python

This might be a really simple question, but I’m using the code below to add 1 day to a date and then output the new date. I found this code online.

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)

this code works but the output its gives me looks like this

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

but for the rest of my code to run properly I need to get rid of the 00:00:00 so I need an output that looks like this

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

It seems like there might be a simple solution but I can’t find it.

Advertisement

Answer

Try using:

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

Check https://www.programiz.com/python-programming/datetime/strftime to learn more.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement