Reputation: 1293
I am trying to pass two dates values that are stored as string to find the number of days within a date range
start = 2019-09-01
end = 2019-09-10
I am trying to pass the above two variable into the below expression and get the below error:
date = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days + 1)]
Error:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Update:
Had to modify the date columns to strings because of the error raised unexpected: ValueError('unconverted data remains: T00:00:00')
Upvotes: 1
Views: 2552
Reputation: 588
from datetime import datetime
Now datetime.strptime(your_date, format)
takes two arguments:- first argument is your date string or your date and the second argument is format like as datetime.strptime("2019-09-11","%Y-%m-%d")
start = '2019-09-01'
end = '2019-09-10'
simply you can do this
start = datetime.strptime(start,"%Y-%m-%d")
end = datetime.strptime(end,"%Y-%m-%d")
total_days = start - end
print(total_days.day)
Upvotes: 0
Reputation: 510
The strptime()
method creates a datetime
object from a given string, which can be used to convert you date strings to the datetime object and then, you can just subtract them to get the delta between them.
https://www.programiz.com/python-programming/datetime/strptime
from datetime import datetime
start = "2019-09-01"
end = "2019-09-10"
dateformat = "%Y-%m-%d"
d0 = datetime.strptime(start, dateformat)
d1 = datetime.strptime(end, dateformat)
delta = d1 - d0
print delta.days
How to calculate number of days between two given dates?
Upvotes: 1
Reputation: 18208
One way to find number of days may be:
from datetime import datetime
start = '2019-09-01'
end = '2019-09-10'
start_date = datetime.strptime(start, '%Y-%m-%d')
end_date = datetime.strptime(end, '%Y-%m-%d')
date_difference = end_date-start_date
# date_difference is timedelta object, you can access days as
print(date_difference.days)
Upvotes: 1
Reputation: 1070
Assuming that your start
and end
objects are str
ings, you can do the following:
from datetime import datetime, timedelta
start = "2019-09-01"
end = "2019-09-10"
# Convert the str dates to actual date objects:
start = datetime.strptime(start, "%Y-%m-%d")
end = datetime.strptime(end, "%Y-%m-%d")
date = [start + timedelta(days=x) for x in range(0, (end - start).days + 1)]
print(date)
# [datetime.datetime(2019, 9, 1, 0, 0), datetime.datetime(2019, 9, 2, 0, 0), datetime.datetime(2019, 9, 3, 0, 0), datetime.datetime(2019, 9, 4, 0, 0), datetime.datetime(2019, 9, 5, 0, 0), datetime.datetime(2019, 9, 6, 0, 0), datetime.datetime(2019, 9, 7, 0, 0), datetime.datetime(2019, 9, 8, 0, 0), datetime.datetime(2019, 9, 9, 0, 0), datetime.datetime(2019, 9, 10, 0, 0)]
Upvotes: 1