0

I'm trying to subtract a day from this date 06-30-2019 in order to make it 06-29-2019 but can't figure out any way to achive that.

I've tried with:

import datetime

date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
print(date)

It surely gives me back the date I used above.

How can I subtract a day from a date in the above format?

robots.txt
  • 96
  • 2
  • 10
  • 36
  • Possible duplicate of [subtract two times in python](https://stackoverflow.com/questions/5259882/subtract-two-times-in-python) – clubby789 Oct 08 '19 at 22:31
  • Possible duplicate of [How to subtract a day from a date?](https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date) – Georgy Oct 09 '19 at 09:21

3 Answers3

1

Your code:

date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')

Check type of date variable.

type(date)
Out[]: str 

It is in string format. To perform subtraction operation you must convert it into date format first. You can use pd.to_datetime()

# Import packages
import pandas as pd
from datetime import timedelta

# input date
date = "06-30-2019"
# Convert it into pd.to_datetime format
date = pd.to_datetime(date)
print(date)
# Substracting days
number_of_days = 1
new_date = date - timedelta(number_of_days)
print(new_date)

output:

2019-06-29 00:00:00

If you want to get rid of timestamp you can use:

str(new_date.date())
Out[]: '2019-06-29'
Sayali Sonawane
  • 12,289
  • 5
  • 46
  • 47
1

try this

import datetime

date = "06/30/19" 
date = datetime.datetime.strptime(date, "%m/%d/%y") 
NewDate = date + datetime.timedelta(days=-1)

print(NewDate)  # 2019-06-29 00:00:00
Daniel Malachov
  • 1,604
  • 1
  • 10
  • 13
0

use timedelta

import datetime
date = datetime.datetime.strptime("06/30/19" ,"%m/%d/%y")
print( date - datetime.timedelta(days=1))
Pooja
  • 1,254
  • 14
  • 17