Jonathan Petts
Jonathan Petts

Reputation: 107

How to subtract from date given as user input?

So I'm trying to subtract one day from a users input of 2018-02-22 for example. Im a little bit stuck with line 5 - my friend who is is leaps and bounds ahead of me suggested I try this method for subtracting one day.

In my online lessons I haven't quite got to datetime yet so Im trying to ghetto it together by reading posts online but got a stuck with the error :

TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument

from datetime import datetime, timedelta

date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date()
new = date1.replace(day=date1.day-1, hour=1, minute=0, second=0, microsecond=0)

print (new)

So my aim is the get the out put 2018-02-21 if I put in 2018-02-22.

Any help would be amazing :)

Upvotes: 0

Views: 1362

Answers (3)

Mustufain
Mustufain

Reputation: 198

    from datetime import datetime, timedelta
    date_entry = input('Enter a date in YYYY-MM-DD format')
    date1 = datetime.strptime(date_entry, '%Y-%m-%d')
    print date1+timedelta(1)

Upvotes: 2

Sociopath
Sociopath

Reputation: 13401

Maybe you need something like this

from datetime import datetime, timedelta

date_entry = input('Enter a date in YYYY-MM-DD format ')

# convert date into datetime object
date1 = datetime.strptime(date_entry, "%Y-%m-%d")  

new_date = date1 -timedelta(days=1)  # subtract 1 day from date

# convert date into original string like format 
new_date = datetime.strftime(new_date, "%Y-%m-%d") 

print(new_date)

Output:

Enter a date in YYYY-MM-DD format 2017-01-01

'2016-12-31'

Upvotes: 1

Vasil
Vasil

Reputation: 38116

First of all a timedeltais best used for the purpose of doing date arithmetcs. You import timedelta but don't use it.

day = timedelta(days=1)
newdate = input_datetime - day

Second problem is you're not initializing a date object properly. But in this case it would be better to use datetime as well as strptime to parse the datetime from the input string in a certain format.

date_entry = input('Enter a date in YYYY-MM-DD format')
input_date = datetime.strptime(date_entry, "%Y-%m-%d")
day = timedelta(days=1)
newdate = input_datetime - day

Upvotes: 2

Related Questions