Home > Blockchain >  Days till year end
Days till year end

Time:12-20

I need to find the numbers of days left from today till the end of the year. I know I can calculate this by simply subtracting today's date from the December 31st of this year, ie:

current_year = dt.datetime.now().year
days_left = dt.date(current_year, 12, 31) - dt.datetime.now().date()

Is there a smarter/faster way to do this?

CodePudding user response:

You may find this a little more concise:

import datetime as dt
from timeit import timeit

def v1():
    today = dt.date.today()
    end_of_year = dt.date(today.year, 12, 31)
    return (end_of_year - today).days

def v2():
    current_year = dt.datetime.now().year
    days_left = dt.date(current_year, 12, 31) - dt.datetime.now().date()
    return days_left.days

for func in v1, v2:
    print(func.__name__, timeit(func))

Output:

v1 0.919826476999333
v2 1.319277847000194
  • Related