In python how to find the total number of days for the last 6 months ?
For example today is 7 November(7 days in this month), and in october there are 31 days and so on until the last 6 months, and now i need to find the total for all the days in a month(until the last 6 months) like
7(Nov) + 31(Oct) + 30(Sep) +... until the last 6 months from now
with dateutil:
>>> from dateutil.relativedelta import relativedelta
>>> import datetime
>>> delta = relativedelta(months=6)
>>> six_month_away = datetime.date.today() - delta
>>> abs((six_month_away - datetime.date.today()).days)
184
Related
I want last friday of each month for upcoming three months.
Friday_date = datetime.date.today()
while Friday_date.weekday() != 4:
Friday_date += datetime.timedelta(1)
This gives me the nearest friday. I want to make sure this is the last friday of this month so that i can add 28 days to get next friday.
The easiest way to do this is to use the module dateutil:
>>> from dateutil.relativedelta import FR, relativedelta
>>> datetime.date.today()+relativedelta(day=31, weekday=FR(-1))
datetime.date(2021, 6, 25)
Don't assume you can get the last Friday of subsequent months just by adding 28 days. It won't always work. Adding 28 days to the last Friday of February 2024 gives you this:
>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), days=28)
datetime.date(2024, 3, 22)
but the last Friday of that month is 29 March. Let dateutil do that correctly for you:
>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), months=1)
datetime.date(2024, 3, 29)
If needed with standard library only, here is with calendar and datetime:
import calendar
from datetime import date
today = date.today()
year, month = today.year, today.month
n_months = 4
friday = calendar.FRIDAY
for _ in range(n_months):
# get last friday
c = calendar.monthcalendar(year, month)
day_number = c[-1][friday] or c[-2][friday]
# display the found date
print(date(year, month, day_number))
# refine year and month
if month < 12:
month += 1
else:
month = 1
year += 1
where the line c[-1][friday] or c[-2][friday] first checks the last week of the month: is Friday nonzero there? if so take it, else look at the week before where there must be a Friday.
This prints
2021-06-25
2021-07-30
2021-08-27
2021-09-24
This formula gets you the day of the last Friday of any given month:
import calendar
year = 2021
month = 6
last_day = calendar.monthrange(year, month)[1]
last_weekday = calendar.weekday(year, month, last_day)
last_friday = last_day - ((7 - (4 - last_weekday)) % 7)
# ^ ^
# | Friday
# days in a week
This is my first coffee, so this can probably be condensed a bit, but it illustrates the logic. last_day is the last calendar day (30 for June), last_weekday is what weekday it is (2 for Wednesday), and based on that we simply calculate how many days to subtract to land on the last Friday (25).
If you want to know the last friday you can do this :
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 4) % 7
last_wednesday = today - timedelta(days=offset)
This question already has answers here:
calculate the difference between two datetime.date() dates in years and months
(3 answers)
Closed 4 years ago.
I have 2 person's birth information, I want to do some analysis on them.
Like, the difference between their age, seconds, years+months+days.
I tried this:
from datetime import date
a = date(1991, 07, 20)
b = date(1999, 06, 06)
print((a-b).days)
-2878
this gives me 2878 days, but i want to calculate years + months + days
i tried to divide 2878/365, but i want the exact calculations
How can i approach this?
Expected Output:
7 years x months x days
Use datetime and dateutil:
from datetime import datetime
from dateutil import relativedelta
date1 = datetime(1991, 7, 20)
date2 = datetime(1999, 6, 6)
diff = relativedelta.relativedelta(date2, date1)
years = diff.years
months = diff.months
days = diff.days
print('{} years {} months {} days'.format(years, months, days))
# 7 years 10 months 17 days
For strict differences, i.e. differences between years, months and days, you can use the attributes of timedelta objects.
from datetime import date
a = date(1991, 7, 20)
b = date(1999, 6, 6)
months = a.month - b.month
years = a.year - b.year
days = a.day - b.day
print('{0} years, {1} months, {2} days'.format(years, months, days))
-8 years, 1 months, 14 days
For time-aware differences, you can use 3rd party dateutil as per #Austin's solution.
Can someone tell me how to get a week number in Python for actual calendar.
Ex: 2016-01-01 to 2016-01-07 = week 1
2016-01-08 to 2016-01-14 = week 2
I tried 2 ways but none of them are working
Using isocalendar()
But that does not work for year end and year start week. For ex:
datetime.date(2016,01,01).isocalendar()[1]
# should be: 1
# got 53
is the following:
dt = date(2016,01,02)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 00
dt = date(2016,01,03)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 01
Both the ways do not satisfy my requirement. Is there any other library I can use to get the week number in Actual Calendar ?
Are you talking about actual number of 7 day periods rather than which week number you're in? Keep in mind in 2016, Jan 3rd is the first day of the second week.
If you're looking at which 7 day period, you should simply count days since the beginning of the year and floor div by 7
dt = datetime.datetime(year=2016, month=1, day=2)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
The 29th should be the first day of week 5. Let's try it.
dt = datetime.datetime(year=2016, month=1, day=29)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
# 5
I'm sure there is an easy way to do this that I have missed with my efforts to find the answer.
Basically how do I get the number of month i.e '05' or '04' from n number of months ago?
Apologies if this was already answered but the questions I researched here could not answer my question.
Edit
There is no month parameter in timedelta, so this did not answer my question.
Martin answered my question perfectly!
With some simple modular arithmetic:
from datetime import date
def months_ago(count):
today = date.today()
return ((today.month - count - 1) % 12) + 1
Demo:
>>> date.today()
datetime.date(2015, 7, 28)
>>> for i in range(13):
... print(months_ago(i))
...
7
6
5
4
3
2
1
12
11
10
9
8
7
While Martijn's answer is perfect for your specific question for anyone who stumbles across this answer looking for a date X months ago rather than just the month's number I would suggest using relativedelta from the third party module dateutil. I have found it quite helpful:
>>> from datetime import date
>>> from dateutil.relativedelta import relativedelta
>>> today = date.today()
datetime.date(2015, 7, 28)
>>> for i in range(13):
print(today - relativedelta(months=i))
2015-07-28
2015-06-28
2015-05-28
2015-04-28
2015-03-28
2015-02-28
2015-01-28
2014-12-28
2014-11-28
2014-10-28
2014-09-28
2014-08-28
2014-07-28
I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.
I tried getting the week number using d1.isocalendar()[1] and subtracting d2.isocalendar()[1] but the issue is that isocalendar()[1] returns December 31, 2012 as week 1 (which supposedly is correct) but that means my logic cannot span over this date.
For reference, here's my complete code:
def week_no(self):
ents = self.course.courselogentry_set.all().order_by('lecture_date')
l_no = 1
for e in ents:
if l_no == 1:
starting_week_of_year = e.lecture_date.isocalendar()[1] # get week of year
initial_year = e.lecture_date.year
if e == self:
this_year = e.lecture_date.year
offset_week = (this_year - initial_year) * 52
w_no = e.lecture_date.isocalendar()[1] - starting_week_of_year + 1 + offset_week
break
l_no += 1
return w_no
With this code, the lecture on Dec 31, 2012 ends up being -35.
How about calculating the difference in weeks between the Mondays within weeks of respective dates? In the following code, monday1 is the Monday on or before d1 (the same week):
from datetime import datetime, timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
print 'Weeks:', (monday2 - monday1).days / 7
Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.
You may want to refer the Python CookBook (2005 edition) Recipe 3.3. The following code snippet is from the cookbook, does what you require.
from dateutil import rrule
import datetime
def weeks_between(start_date, end_date):
weeks = rrule.rrule(rrule.WEEKLY, dtstart=start_date, until=end_date)
return weeks.count()
This is a very simple solution with less coding everyone would understand.
from datetime import date
d1 = date(year, month, day)
d2 = date(year, month, day)
result = (d1-d2).days//7
The solution above has a bug (I can't add a comment due to low reputation). It doesn't account for hour differences.
# This code has a bug.
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
Counter example of 2 dates more than a week apart:
Timestamp1: 1490208193270795 (22 Mar 2017 18:43:13 GMT)
Monday1: 20 Mar 2017 18:43:13 GMT
Timestamp2: 1489528488744290 (14 Mar 2017 21:54:48 GMT)
Monday2: 13 Mar 2017 21:54:48 GMT
Using that code it returns 0 as week diff when it should be 1. Need to zero out the hours/minutes/seconds as well.
To determine how many weeks are spanned by two dates. eg From 3rd Oct to 13th Oct
October 2015
Mo 5 12 19 26
Tu 6 13 20 27
We 7 14 21 28
Th 1 8 15 22 29
Fr 2 9 16 23 30
Sa 3 10 17 24 31
Su 4 11 18 25
Code:
import math, datetime
start_date = datetime.date(2015, 10, 3)
start_date_monday = (start_date - datetime.timedelta(days=start_date.weekday()))
end_date = datetime.date(2015, 10, 13)
num_of_weeks = math.ceil((end_date - start_date_monday).days / 7.0)
Equals 3 weeks.
You're a bit vague on what 'difference in weeks' means exactly. Is 6 days difference one week or zero ? Is eight days difference one week or two ?
In any case, why can't you simply find the difference in another unit (seconds or days) and divide by the appropriate amount, with your prefered rounding for weeks?
Edited Best Answer
from datetime import timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
diff = monday2 - monday1
noWeeks = (diff.days / 7) + math.ceil(diff.seconds/86400)
print('Weeks:', noWeeks)`