0

Right now I have this code. I am intending to write code that calculates the number of days between today and January 1 of this year.

As you can see in the output below, it prints the number of days and the time.

How can I rewrite the code so that it says just '78', not '78 days, 21:04:08.256440'?

from datetime import datetime
Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)

print(NumberOfDays)


#Output: 78 days, 21:04:08.256440
Bugs
  • 4,491
  • 9
  • 32
  • 41
iii
  • 17
  • 6

2 Answers2

1

Here's a working Fiddle.

As jpp commented on your question you had to use print(NumberOfDays.days). But be careful, in your solution it return 78 (on the 20/03/2018) but it is the 79th day (starting from 1).

Another simpler way to do it is : print(datetime.now().timetuple().tm_yday)

And another even simpler way to do it : print(Now.strftime('%j'))

from datetime import datetime

Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)

print(NumberOfDays.days)                     # 78
print(datetime.now().timetuple().tm_yday)    # 79
print(Now.strftime('%j'))                    # 079
Antoine Thiry
  • 2,362
  • 4
  • 28
  • 42
0
import datetime
today = datetime.date.today()
first_day = datetime.date(year=today.year, month=1, day=1)
diff = today - first_day
print(diff)

78 days, 0:00:00
Samuel Muiruri
  • 492
  • 1
  • 8
  • 17