Tell me why the result of executing such code: 10

import datetime def get_days_passed(date_string): input_date = datetime.datetime( int(date_string[:4]), int(date_string[5:7]), int(date_string[8:10]) ) return (datetime.datetime.today()-input_date).days if __name__ == '__main__': print(get_days_passed('2018-01-12')) # output: 10 

And the result of this is 0:

 def get_days_passed(date_string): input_date = datetime.datetime.strptime(date_string, '%Y-%m-%d') return (datetime.datetime.today()-input_date).days if __name__ == '__main__': print(get_days_passed('2018-01-12')) # output: 0 

enter image description here

  • Why so hard? datetime.datetime.strptime('2018-01-12', '%Y-%m-%d') - MaxU
  • Well, yes, I just indicated below such an option, I want to understand why the logic does not work in a complex variation. Spent an hour and a half of my life. If I don’t figure it out, it will be very difficult) - Serg4356
  • one
    look at the indexes carefully - jfs
  • one
    @ Serg4356, you have another code on the screenshot;) date_string[9:10] - will return 4 - that's the whole secret ... - MaxU
  • one
    Exactly, thanks to everyone) Apparently when I changed indices I changed only those that were in print - Serg4356

1 answer 1

If you need to calculate the difference between one day and another day, there is a timedelta in datetime for it, try it:

 from datetime import timedelta d = timedelta(microseconds=-1) (d.days, d.seconds, d.microseconds) 

Output: (-1, 86399, 999999)

The code is stolen from here.