saltcracker
saltcracker

Reputation: 321

Datetime and Stfrtime

I'm making a calculator which tells you how many days there is between today and the given date. The dates is imported from a file and is written in format yyyy/mm/dd and dd/mm/yyyy.

I have two problems:

1: The format which the dates are written in varies. A few of the dates is written in reverse. How do I reverse them? I get ValueError: day is out of range for month.

2: When I try to subtract "today" with the "dates" I get the error TypeError: unsupported operand type(s) for -: 'str' and 'str' and when I add "int" I get ValueError: invalid literal for int() with base 10: '2015, 10, 23'

Any advice? :)

for line in response:
 line = (line.decode(encoding).strip())
 year, month, day = line.split('/')

 today = date.today().strftime("%Y, %m, %d")
 dates = datetime(int(year), int(month), int(day)).strftime("%Y, %m, %d")

 print(int(today)-int(dates))

Upvotes: 0

Views: 1014

Answers (2)

R Nar
R Nar

Reputation: 5515

Your second problem is caused by calling strftime too early. date objects can be evaluated to each other, but strings cannot. ie

today = date.today()
dates = date(int(year), int(month), int(day))

print((today-dates).days)

also, you should use date objects for both.

You're second problem can be fixed with some simple error checking like

if year < day:
  switch(year,day) #pseudo code

or something more verbose than that but you get the idea.

EDIT: I forgot that comparisons return a timedelta object. these objects only hold days and smaller time sequences (hours, mins, seconds etc)

Upvotes: 1

Pavan Gupta
Pavan Gupta

Reputation: 19233

No need to convert into integer if you have two date objects, you can just subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

Upvotes: 1

Related Questions