简体   繁体   中英

Days till year end

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM