get the date for the first day of the current decade in python

To get the date for the first day of the current decade in Python, we can utilize the datetime module to perform date arithmetic. Here's the code to do it:

main.py
import datetime

# get the current year
current_year = datetime.datetime.now().year

# calculate the start year of the current decade
start_year = (current_year // 10) * 10

# create a datetime object for the first day of the decade
first_day_of_decade = datetime.datetime(start_year, 1, 1)

print(first_day_of_decade)
319 chars
13 lines

This code first gets the current year using datetime.datetime.now().year. It then calculates the start year of the current decade by dividing the current year by 10, rounding down to the nearest integer, and multiplying by 10. This gives us the first year of the current decade (e.g. 2020 for the decade 2020-2029).

We then create a new datetime object for the first day of the decade using datetime.datetime(start_year, 1, 1), which sets the year to the start year of the decade, the month to 1 (January), and the day to 1 (the first day of the month).

Finally, we print the first_day_of_decade datetime object to the console, which should output something like 2020-01-01 00:00:00.

gistlibby LogSnag