Calculate 38 days from month last date in Django [duplicate] - python

This question already has answers here:
how to calculate 38 days from next month starting in Python
(4 answers)
Closed 1 year ago.
let us consider date as
invoice.created_at = datetime.date(2021, 11, 17)
next_month_first_date here is getting the nextmonth first date
next_month_first_date = (invoice.created_at.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)
# datetime.date(2021, 12, 1)
Now I need last day of invoice.created_at month
this_month_last_day = ?
how to find last date of invoice.created_at month i.e 30/11/2021 and calculate 38 days from this_month_last_day? 38 days from this_month_last_day is 7/01/2022

Since you already have the 1st day of the next month you can simply subtract 1 day from this to get the last day of the current month:
this_month_last_day = next_month_first_date - datetime.timedelta(days=1)
>>> this_month_last_day + datetime.timedelta(days=38)
datetime.date(2022, 1, 7)

You can use Python's calender module to get the last day of the month
import calendar
import datetime
created_at = datetime.date(2021, 11, 17)
last_day_as_int = calendar.monthrange(created_at.year, created_at.month)[1] # 30
last_day_as_date = created_at.replace(day=last_day_as_int) # datetime.date(2021, 11, 30)
target_date = last_day_as_date + datetime.timedelta(days=38) # datetime.date(2022, 1, 7)

Related

Pyspark : get next_day from a variable

I use deltatime to subtract 12 weeks and get the exact date
but from this date I have to recover on Friday. this means that if we subtract 12 weeks I have Monday January 3, I have to make a change to get Friday January 7.
Code exemple :
I use this code to get the initial date :
week_num_period = datetime.today()- timedelta(weeks=12)
week_start_perioddddd = week_num_period.strftime("%Y-%m-%d")
but from that date i need to get the friday of that week !
i tried with
week_start_period = next_day(week_start_perioddddd, 'Friday')
week_start_period
but next_day doesn't apply on str !
could someone help me ?
So you want to get the formatted date for the Friday from the week 12 weeks ago?
Add the timedelta of: 4 (weekday index of Friday) minus the weekday index of the day you calculated.
>>> week_num_period = datetime.today()- timedelta(weeks=12)
>>> week_num_period.date()
datetime.date(2022, 1, 6)
>>> friday = week_num_period + timedelta(days=4 - week_num_period.weekday())
>>> friday.date()
datetime.date(2022, 1, 7)
>>> week_start_period = friday.strftime("%Y-%m-%d")
>>> week_start_period
'2022-01-07'
>>>

Is there a better way to determine day in future using integer values

Here is the problem:
If the int values [0,7) (0, 1, 2, 3, 4, 5, 6) refer to Monday through
Sunday, and today is Monday, what day of the week will it be in 999
days?
Here is how I solved it:
import datetime
#Capture the First Date
day1 = datetime.date(2021, 1, 25)
print('day1:', day1.ctime())
# Capture the Second Date
day2 = datetime.date(2023, 10, 21)
print('day2:', day2.ctime())
# Find the difference between the dates
print('Number of Days:', day1-day2)
Returns:
day1: Mon Jan 25 00:00:00 2021
day2: Sat Oct 21 00:00:00 2023
Number of Days: -999 days, 0:00:00
Use timedelta to add n days from your "start date":
from datetime import date, timedelta
current = date.today()
future = current + timedelta(days=999)
print(f"{current=}", current.weekday(), current.strftime("%A"))
print(f"{future=}", future.weekday(), future.strftime("%A"))
Output:
current=datetime.date(2021, 1, 24) 6 Sunday
future=datetime.date(2023, 10, 20) 4 Friday
.weekday() returns the day of the week as an integer.
.strftime("%A") will format a date object as a Weekday name.

6 month before date in python [duplicate]

This question already has answers here:
How do I calculate the date six months from the current date using the datetime Python module?
(47 answers)
Closed 7 years ago.
I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like date=now - timedelta(days=days) instead of argument days.
timedelta does not support months, but you can try using dateutil.relativedelta for your calculations , which do support months.
Example -
>>> from dateutil import relativedelta
>>> from datetime import datetime
>>> n = datetime.now()
>>> n - relativedelta.relativedelta(months=6)
datetime.datetime(2015, 1, 30, 10, 5, 32, 491815)
>>> n - relativedelta.relativedelta(months=8)
datetime.datetime(2014, 11, 30, 10, 5, 32, 491815)
If you are only interested in what the month was 6 months ago then try this:
import datetime
month = datetime.datetime.now().month - 6
if month < 1:
month = 12 + month # At this point month is 0 or a negative number so we add
Following function should work fine for both month add and month substract.
import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
#Example: Get today
dateToday = datetime.date.today()
#Substract 6 month from Today
print add_months(dateToday ,-6)

Check if it is the end of the month in python

I am writing code to take data from the last year. I want to round up the earlier date like so: If it is July 14 2015, I want data from August 1st 2014-July 14,2015
df = pd.read_csv('MyData.csv')
df['recvd_dttm'] = pd.to_datetime(df['recvd_dttm'])
range_max = datetime.datetime.now()
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)
if datetime.datetime.now() == is_month_end:
# take slice with final week of data
df = df[(df['recvd_dttm'] >= range_min) &
(df['recvd_dttm'] <= range_max)]
My problem is that when it is July 31, 2015, my code goes to the end of the next month, essentially cutting out an entire month.
I am trying to make a for loop to fix this problem.
If it is the end of the month:
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)
else:
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)
How do I tell python to check for the end of the month? MonthEnd is only an offset function.
We can avoid importing the calendar module with a short function that only leverages datetime.
If tomorrow's month is not the same as today's month, then that means today is the last day of the current month. We can check this programmatically with a short function such as
import datetime
def end_of_month(dt):
todays_month = dt.month
tomorrows_month = (dt + datetime.timedelta(days=1)).month
return tomorrows_month != todays_month
Now, for your specific use case:
now = datetime.datetime.now()
if end_of_month(now):
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)
else:
range_min = range_max - pd.tseries.offsets.DateOffset(years=1) +pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)
I simply would use the monthrange method of calendar module to find last day number of the month:
def check_if_last_day_of_week(date):
import datetime
import calendar
# calendar.monthrange return a tuple (weekday of first day of the
# month, number
# of days in month)
last_day_of_month = calendar.monthrange(date.year, date.month)[1]
# here i check if date is last day of month
if date == datetime.date(date.year, date.month, last_day_of_month):
return True
return False
>>> date = datetime.date(2018, 12, 31)
>>> check_if_last_day_of_week(date)
True
If the next day is a different month, it means it is the last day of a month.
def check_if_last_day_of_month(to_date):
delta = datetime.timedelta(days=1)
next_day = to_date + delta
if to_date.month != next_day.month:
return True
return False
I was using Pandas and I did not want to include another library, so I used this to check whether is the last day of the month and last day of the year:
import pandas as pd
my_date = '31-12-2021'
current_data = pd.to_datetime(my_date, format='%d-%m-%Y')
current_month = current_data.month
current_year = current_data.year
following_day = current_data + pd.DateOffset(1)
tomorrows_month = following_day.month
tomorrows_year = following_day.year
is_last_day_of_month = True if tomorrows_month != current_month else False
is_last_day_of_year = True if tomorrows_year != current_year else False
Here's a pure python approach that also takes into account leap years for february:
# total days in every month during non leap years
M_DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isleap(year):
"""Return True for leap years, False for non-leap years."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
"""Returns total number of days in a month accounting for leap years."""
return M_DAYS[month] + (month == 2 and isleap(year))
def is_monthend(ref_date):
"""Checks whether a date is also a monthend"""
return ref_date.day == days_in_month(ref_date.year, ref_date.month)
Alright, here's what I did. Found the calendar module that BryanOakley suggested and made this loop. It checks the current day and checks if it is the same as the last day of the month, and chooses the range_min accordingly.
if datetime.datetime.now().day == calendar.monthrange(date.year, date.month)[1]:
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.DateOffset(days=1)
else:
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)
import datetime
def find_curr_month_end_date(curr_date):
if(curr_date.month != 12):
next_month_first_date= curr_date.replace(day=1).replace(month=curr_date.month+1)
else:
next_month_first_date= curr_date.replace(day=1).replace(month=1).replace(year=curr_date.year+1)
curr_month_end_date = next_month_first_date - datetime.timedelta(days=1)
return curr_month_end_date
curr_date = datetime.datetime.today()
# or curr_date = datetime.datetime.strptime("2020-12-16","%Y-%m-%d")
curr_month_end_date =
find_curr_month_end_date(curr_date)
Here is a short function to accomplish this. It requires the dateutil module so that you can do relative date math.
import datetime
from dateutil.relativedelta import relativedelta
def lastyear_period_start(current_date):
last_year = current_date - relativedelta(months=11)
return datetime.date(last_year.year, last_year.month, 1)
It can be utilized like so:
dates = [
datetime.datetime(2010, 2, 27),
datetime.datetime(2011, 2, 27),
datetime.datetime(2012, 2, 27),
datetime.datetime(2013, 2, 27),
datetime.datetime(2014, 2, 27),
datetime.datetime(2010, 7, 27),
datetime.datetime(2011, 7, 27),
datetime.datetime(2012, 7, 27),
datetime.datetime(2013, 7, 27),
datetime.datetime(2014, 7, 27),
datetime.datetime(2015, 7, 14),
datetime.datetime(2015, 7, 31),
datetime.datetime(2011, 2, 28),
datetime.datetime(2012, 2, 29),
datetime.datetime(2013, 2, 28),
]
for d in dates:
print d, lastyear_period_start(d)
This prints that following
2010-02-27 00:00:00 2009-03-01
2011-02-27 00:00:00 2010-03-01
2012-02-27 00:00:00 2011-03-01
2013-02-27 00:00:00 2012-03-01
2014-02-27 00:00:00 2013-03-01
2010-07-27 00:00:00 2009-08-01
2011-07-27 00:00:00 2010-08-01
2012-07-27 00:00:00 2011-08-01
2013-07-27 00:00:00 2012-08-01
2014-07-27 00:00:00 2013-08-01
2015-07-14 00:00:00 2014-08-01
2015-07-31 00:00:00 2014-08-01
2011-02-28 00:00:00 2010-03-01
2012-02-29 00:00:00 2011-03-01
2013-02-28 00:00:00 2012-03-01
In the function we're doing two simple steps
last_year = current_date - relativedelta(months=11)
First we find out what the date was 11 months ago, based on the date passed to the function
return datetime.date(last_year.year, last_year.month, 1)
Then we return the first day of that month.
In the output above you can see this accounts for leap years as well.

Get next and last ISO week number in a year

By this I am getting current week number
datetime.date(2014, 9, 30).isocalendar()[1]
but I want to get what is next ISO week number and max ISO week number in current year in python.
I can't add current week number + 1 to get next week number, because it may be that year doesn't have that week number.
To get next week's week number, add a timedelta:
>>> import datetime
>>> today = datetime.date(2014, 9, 30)
>>> next_week = today + datetime.timedelta(days=7)
>>> next_week.isocalendar()[1]
41
To get the last week number in the year, note that the following rule is used:
The following years have 53 weeks:
years starting with Thursday
leap years starting with Wednesday

Categories