Deducting x number of months from a given date - python

Is there a way to deduct a specified number of months from a given date. So for example, if the day is 2006/02/27. Then I want to backtrack 3 months and find the months within this date and 3 months back. In this case, it would be Feb, Jan & dec. What I am really after is finding a range of months.
I can think of using timedelta and specifying 93 days (31 x 3). But this could potentially be a problem if its early month date. something like 01/03/2006 - 93 days will perhaps result in a date in november/2005, which will include march, Feb,Jan,Dec,Nov as months. But what I want is March,Feb and Jan
from datetime import datetime,timedelta
someDate = datetime(2006,2,27)
newDate =someDate - timedelta(days = 3)
#someDate - 3months
Any ideas on how to solve?

Related

Get number of days in a specific month that are in a date range

Haven't been able to find an answer to this problem. Basically what I'm trying to do is this:
Take a daterange, for example October 10th to November 25th. What is the best algorithm for determining how many of the days in the daterange are in October and how many are in November.
Something like this:
def daysInMonthFromDaterange(daterange, month):
# do stuff
return days
I know that this is pretty easy to implement, I'm just wondering if there's a very good or efficient algorithm.
Thanks
Borrowing the algorithm from this answer How do I divide a date range into months in Python?
, this might work. The inputs are in date format, but can be changed to date strings if preferred:
import datetime
begin = '2018-10-10'
end = '2018-11-25'
dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
#print(today)
tomorrow = today + one_day
if tomorrow.month != today.month:
start_dates.append(tomorrow)
end_dates.append(today)
today = tomorrow
end_dates.append(dt_end)
out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
diff = (end - start).days
print('{} to {}: {} days'.format(start.strftime(out_fmt), end.strftime(out_fmt), diff))
result:
10 October 2018 to 31 October 2018: 21 days
01 November 2018 to 25 November 2018: 24 days
The problem as stated may not have a unique answer. For example what should you get from daysInMonthFromDaterange('Feb 15 - Mar 15', 'February')? That will depend on the year!
But if you substitute actual days, I would suggest converting from dates to integer days, using the first of the month to the first of the next month as your definition of a month. This is now reduced to intersecting intervals of integers, which is much easier.
The assumption that the first of the month always happened deals with months of different lengths, variable length months, and even correctly handles the traditional placement of the switch from the Julian calendar to the Gregorian. See cal 1752 for that. (It will not handle that switch for all locations though. Should you be dealing with a library that does Romanian dates in 1919, you could have a problem...)
You can use the datetime module:
from datetime import datetime
start = datetime(2018,10,10)
end = datetime(2018,11,25)
print((end - start).days)
Something like this would work:
def daysInMonthFromDaterange(date1, date2, month):
return [x for x in range(date1.toordinal(), date2.toordinal()) if datetime.date.fromordinal(x).year == month.year and datetime.date.fromordinal(x).month == month.month]
print(len(days_in_month(date(2018,10,10), date(2018,11,25), date(2018,10,01))))
This just loops through all the days between date1 and date2, and returns it as part of a list if it matches the year and month of the third argument.

Python - Determine

I am trying to identify the month number from a given week and year number (both are user inputs). The script needs to be written in python.
eg - 1) Yr 2017, Wk 12 results in Month# 3
2) Yr 2017, Wk 32 results in Month#8 and so on
I am a newbie and searched for all date time examples, still no clue. Any ideas? Would really appreciate the help.
Thanks in advance!
As we know the numbers of days in each month of a given year, and the number of days that span w weeks (w*7) it is sufficient to sum the days of each month until the result is greater than w*7, counting the number of months used in the sum. If we used say n months, the number you want is n
We can know if the year is a leap year as the following demonstrates.
import calendar
print calendar.isleap(2017)

How to use day of the week and the day of the month to get year in python?

for example how would you get "2016" from
Fri, Feb, 19 ?
I have a database from somewhere that has entries from the last 4 years but only lists dates as day of the week and day of the month, and I need to get the year from each. There should not be any repetitions because there is only four years of data, and date & day of the week alignments do not repeat in that timeframe.
How about this:
import datetime
year = next(date for year in (2013, 2014, 2015, 2016)
for date in (datetime.date(year, 2, 19),)
if date.weekday() == 4).year
This is just slightly different from #zondo's answer who beats me to it, but I'll put this up anyway because I prefer not to have the .year at the end of a long expression:
year = next(y for y in range(2013, 2017) if datetime.date(y, 2, 19).weekday() == 4)

Output all dates for a date range [duplicate]

This question already has answers here:
Generate a list of datetimes between an interval
(5 answers)
Closed 8 years ago.
I have a starting date (lets say January 5th 2014) and an end date (lets say July 10th 2014). I know that an event occurs every Wednesday. Is there an easy way in Python to output all Wednesday with date between those date ranges?
So assuming January 7th is a Wednesday, then the code snippet would output 01.07.2014, 01.14.2014, 01.21.2014, and so on.
To get the first specific weekday after a given date, just add a timedelta of the difference in the weekdays:
wed = 2 # from the datetime.weekday definition
first_wed = start + datetime.timedelta(days=(7 + wed - start.weekday()) % 7)
Once you have that, please see Generate a list of datetimes between an interval in python.

Get week number using date in python

Date is datetime.date(2013, 12, 30)
I am trying to get week number using
import datetime
datetime.date(2013, 12, 30).isocalendar()[1]
I am getting output as ,
1
Why i am not getting week number of last year , instead i am getting week number of current year?
Whats wrong i am doing here ?
You are doing nothing wrong, 2013/12/30 falls in week 1 of 2014, according to the ISO8601 week numbering standard:
The ISO 8601 definition for week 01 is the week with the year's first Thursday in it.
The Thursday in that week is 2014/01/02.
Other ways to explain the definition, from the same linked WikiPedia article:
It is the first week with a majority (four or more) of its days in January (ISO weeks start on Monday)
Its first day is the Monday nearest to 1 January.
It has 4 January in it. Hence the earliest possible dates are 29 December through 4 January, the latest 4 through 10 January.
It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days.
If you were looking for the last week number of a given year (52 or 53, depending on the year), I'd use December 28th, which is always guaranteed to be in the last week (because January 4th is always part of the first week of the next year):
def lastweeknumber(year):
return datetime.date(year, 12, 28).isocalendar()[1]
from datetime import date
from datetime import datetime
ndate='10/1/2016'
ndate = datetime.strptime(ndate, '%m/%d/%Y').strftime('%Y,%m,%d')
print('new format:',ndate)
d=ndate.split(',')
wkno = date(int(d[0]),int(d[1]),int(d[2])).isocalendar()[1]
print(wkno)
manually or read a date to a string and get the week number, play around with different formats.

Categories