I have a date in the format "YYYY-MM-DD"
, for example "2022-03-09"
. It is the 68th day of the year 2022. Is there a way to get the 68th day of 2021? More generally, if I have a date in "YYYY-MM-DD"
format, which is the N th day of the year, is there a quick way to calculate the N th day of the previous year?
CodePudding user response:
You could do:
from datetime import datetime, timedelta
date_string = '2020-03-09'
# Parse the string to a datetime.date object
date = datetime.strptime(date_string, '%Y-%m-%d')
# Get the number N of the day in the year
N = date.timetuple().tm_yday
# Take 1st of january of last year and add N-1 days
N_last_year = (
date.replace(year=date.year-1, month=1, day=1)
timedelta(days=N-1)
)
print(N_last_year.date())
Or, another funny solution based on leap years. It is based on the fact that the Nth day of last year is the same as this year's, except if the date is after 29th february and there is a leap year somewhere.
from datetime import datetime, timedelta
def leap(year: int) -> bool:
# Returns True if year is a leap year, False otherwise
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
date_string = '2020-03-09'
# Parse the string to a datetime.date object
date = datetime.strptime(date_string, '%Y-%m-%d')
# Get the number N of the day in the year
N = date.timetuple().tm_yday
date_last_year = date.replace(year=date.year-1)
# Do the cool thing
if date.month >= 3:
if leap(date.year):
date_last_year = timedelta(days=1)
elif leap(date.year-1):
date_last_year = timedelta(days=-1)
print(date_last_year.date())
CodePudding user response:
The datetime
objects will you with that (https://docs.python.org/3/library/datetime.html).
Indeed, you can compute the time lap between your date and the beginning of the year. Then you can add this difference to the beginning of the next year.
import datetime
date_string = "2022-03-09"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d").date()
beginning_of_year = datetime.date(date_object.year, 1, 1)
time_difference = date_object - beginning_of_year
beginning_of_last_year = datetime.date(date_object.year - 1, 1, 1)
same_day_last_year = beginning_of_last_year time_difference
print(same_day_last_year)
However, the result is disappointing, since it is in fact the same date...
CodePudding user response:
I think you can do something like
from datetime import timedelta, date
year = timedelta(days=365)
today = date.fromisoformat("2022-03-09")
print(today - year)