Related
I'm using the datetime module, i.e.:
>>> import datetime
>>> today = datetime.datetime.now()
>>> print(today)
2009-03-06 13:24:58.857946
and I would like to compute the day of year that takes leap years into account. e.g. today (March 6, 2009) is the 65th day of 2009.
I see a two options:
Create a number_of_days_in_month = [31, 28, ...] array, decide if it's a leap year and manually sum up the days.
Use datetime.timedelta to make a guess & then binary search for the correct day of the year:
>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating the day of the year. Any ideas/suggestions?
Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:
from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday # returns 1 for January 1st
You could use strftime with a %j format string:
>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'
but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.
DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.
I found this to work:
import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')
>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday
>>>> 77
Or numerically:
import datetime
year,julian = [1936,77]
datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)
>>>> datetime.datetime(1936, 3, 17, 0, 0)
Or with fractional 1-based jdates popular in some domains:
jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
display(jdate_frac)
>>>> 77.5515625
year,julian = [1936,jdate_frac]
display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))
>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.
If you have reason to avoid the use of the datetime module, then these functions will work.
def is_leap_year(year):
""" if year is a leap year return True
else return False """
if year % 100 == 0:
return year % 400 == 0
return year % 4 == 0
def doy(Y,M,D):
""" given year, month, day return day of year
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
return N
def ymd(Y,N):
""" given year = Y and day of year = N, return year, month, day
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
M = int((9 * (K + N)) / 275.0 + 0.98)
if N < 32:
M = 1
D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return Y, M, D
I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
(...)
823 1508 11334 7.5 41.6 yday = int(period_end.strftime('%j'))
824 1508 2492 1.7 9.1 yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
825 1508 1852 1.2 6.8 yday = (period_end - date(period_end.year, 1, 1)).days + 1
826 1508 5078 3.4 18.6 yday = period_end.timetuple().tm_yday
(...)
So most efficient is
yday = (period_end - date(period_end.year, 1, 1)).days + 1
Just subtract january 1 from the date:
import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1
You may simple use dayofyear attribute provided by "pandas" which in turn give you the day of the year for a particular year.
For e.g.
data["day_of_year"] = data.Datetime.apply(lambda x:x.dayofyear)
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 need to increment the month of a datetime value
next_month = datetime.datetime(mydate.year, mydate.month+1, 1)
when the month is 12, it becomes 13 and raises error "month must be in 1..12". (I expected the year would increment)
I wanted to use timedelta, but it doesn't take month argument.
There is relativedelta python package, but i don't want to install it just only for this.
Also there is a solution using strtotime.
time = strtotime(str(mydate));
next_month = date("Y-m-d", strtotime("+1 month", time));
I don't want to convert from datetime to str then to time, and then to datetime; therefore, it's still a library too
Does anyone have any good and simple solution just like using timedelta?
This is short and sweet method to add a month to a date using dateutil's relativedelta.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date_after_month = datetime.today()+ relativedelta(months=1)
print('Today: ',datetime.today().strftime('%d/%m/%Y'))
print('After Month:', date_after_month.strftime('%d/%m/%Y'))
Today: 01/03/2013
After Month: 01/04/2013
A word of warning: relativedelta(months=1) and relativedelta(month=1) have different meanings. Passing month=1 will replace the month in original date to January whereas passing months=1 will add one month to original date.
Note: this will require python-dateutil module. If you are on Linux you need to run this command in the terminal in order to install it.
sudo apt-get update && sudo apt-get install python-dateutil
Explanation : Add month value in python
Edit - based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:
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)
In use:
>>> somedate = datetime.date.today()
>>> somedate
datetime.date(2010, 11, 9)
>>> add_months(somedate,1)
datetime.date(2010, 12, 9)
>>> add_months(somedate,23)
datetime.date(2012, 10, 9)
>>> otherdate = datetime.date(2010,10,31)
>>> add_months(otherdate,1)
datetime.date(2010, 11, 30)
Also, if you're not worried about hours, minutes and seconds you could use date rather than datetime. If you are worried about hours, minutes and seconds you need to modify my code to use datetime and copy hours, minutes and seconds from the source to the result.
Here's my salt :
current = datetime.datetime(mydate.year, mydate.month, 1)
next_month = datetime.datetime(mydate.year + int(mydate.month / 12), ((mydate.month % 12) + 1), 1)
Quick and easy :)
since no one suggested any solution, here is how i solved so far
year, month= divmod(mydate.month+1, 12)
if month == 0:
month = 12
year = year -1
next_month = datetime.datetime(mydate.year + year, month, 1)
Use the monthdelta package, it works just like timedelta but for calendar months rather than days/hours/etc.
Here's an example:
from monthdelta import MonthDelta
def prev_month(date):
"""Back one month and preserve day if possible"""
return date + MonthDelta(-1)
Compare that to the DIY approach:
def prev_month(date):
"""Back one month and preserve day if possible"""
day_of_month = date.day
if day_of_month != 1:
date = date.replace(day=1)
date -= datetime.timedelta(days=1)
while True:
try:
date = date.replace(day=day_of_month)
return date
except ValueError:
day_of_month -= 1
from datetime import timedelta
try:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=x.day)
except ValueError: # January 31 will return last day of February.
next = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
If you simply want the first day of the next month:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=1)
To calculate the current, previous and next month:
import datetime
this_month = datetime.date.today().month
last_month = datetime.date.today().month - 1 or 12
next_month = (datetime.date.today().month + 1) % 12 or 12
Perhaps add the number of days in the current month using calendar.monthrange()?
import calendar, datetime
def increment_month(when):
days = calendar.monthrange(when.year, when.month)[1]
return when + datetime.timedelta(days=days)
now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)
What about this one? (doesn't require any extra libraries)
from datetime import date, timedelta
from calendar import monthrange
today = date.today()
month_later = date(today.year, today.month, monthrange(today.year, today.month)[1]) + timedelta(1)
Simplest solution is to go at the end of the month (we always know that months have at least 28 days) and add enough days to move to the next moth:
>>> from datetime import datetime, timedelta
>>> today = datetime.today()
>>> today
datetime.datetime(2014, 4, 30, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2014, 5, 30, 11, 47, 27, 811253)
Also works between years:
>>> dec31
datetime.datetime(2015, 12, 31, 11, 47, 27, 811253)
>>> today = dec31
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
Just keep in mind that it is not guaranteed that the next month will have the same day, for example when moving from 31 Jan to 31 Feb it will fail:
>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
So this is a valid solution if you need to move to the first day of the next month, as you always know that the next month has day 1 (.replace(day=1)). Otherwise, to move to the last available day, you might want to use:
>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> next_month = (today.replace(day=28) + timedelta(days=10))
>>> import calendar
>>> next_month.replace(day=min(today.day,
calendar.monthrange(next_month.year, next_month.month)[1]))
datetime.datetime(2016, 2, 29, 11, 47, 27, 811253)
Similar in ideal to Dave Webb's solution, but without all of that tricky modulo arithmetic:
import datetime, calendar
def increment_month(date):
# Go to first of this month, and add 32 days to get to the next month
next_month = date.replace(day=1) + datetime.timedelta(32)
# Get the day of month that corresponds
day = min(date.day, calendar.monthrange(next_month.year, next_month.month)[1])
return next_month.replace(day=day)
This implementation might have some value for someone who is working with billing.
If you are working with billing, you probably want to get "the same date next month (if possible)" as opposed to "add 1/12 of one year".
What is so confusing about this is you actually need take into account two values if you are doing this continuously. Otherwise for any dates past the 27th, you'll keep losing a few days until you end up at the 27th after leap year.
The values you need to account for:
The value you want to add a month to
The day you started with
This way if you get bumped from the 31st down to the 30th when you add one month, you'll get bumped back up to the 31st for the next month that has that day.
This is how I did it:
def closest_date_next_month(year, month, day):
month = month + 1
if month == 13:
month = 1
year = year + 1
condition = True
while condition:
try:
return datetime.datetime(year, month, day)
except ValueError:
day = day-1
condition = day > 26
raise Exception('Problem getting date next month')
paid_until = closest_date_next_month(
last_paid_until.year,
last_paid_until.month,
original_purchase_date.day) # The trick is here, I'm using the original date, that I started adding from, not the last one
Well with some tweaks and use of timedelta here we go:
from datetime import datetime, timedelta
def inc_date(origin_date):
day = origin_date.day
month = origin_date.month
year = origin_date.year
if origin_date.month == 12:
delta = datetime(year + 1, 1, day) - origin_date
else:
delta = datetime(year, month + 1, day) - origin_date
return origin_date + delta
final_date = inc_date(datetime.today())
print final_date.date()
I was looking to solve the related problem of finding the date for the first of the following month, regardless of the day in the given date. This does not find the same day 1 month later.
So, if all you want is to put in December 12, 2014 (or any day in December) and get back January 1, 2015, try this:
import datetime
def get_next_month(date):
month = (date.month % 12) + 1
year = date.year + (date.month + 1 > 12)
return datetime.datetime(year, month, 1)
A solution without the use of calendar:
def add_month_year(date, years=0, months=0):
year, month = date.year + years, date.month + months + 1
dyear, month = divmod(month - 1, 12)
rdate = datetime.date(year + dyear, month + 1, 1) - datetime.timedelta(1)
return rdate.replace(day = min(rdate.day, date.day))
def add_month(d,n=1): return type(d)(d.year+(d.month+n-1)/12, (d.month+n-1)%12+1, 1)
Just Use This:
import datetime
today = datetime.datetime.today()
nextMonthDatetime = today + datetime.timedelta(days=(today.max.day - today.day)+1)
This is what I came up with
from calendar import monthrange
def same_day_months_after(start_date, months=1):
target_year = start_date.year + ((start_date.month + months) / 12)
target_month = (start_date.month + months) % 12
num_days_target_month = monthrange(target_year, target_month)[1]
return start_date.replace(year=target_year, month=target_month,
day=min(start_date.day, num_days_target_month))
def month_sub(year, month, sub_month):
result_month = 0
result_year = 0
if month > (sub_month % 12):
result_month = month - (sub_month % 12)
result_year = year - (sub_month / 12)
else:
result_month = 12 - (sub_month % 12) + month
result_year = year - (sub_month / 12 + 1)
return (result_year, result_month)
def month_add(year, month, add_month):
return month_sub(year, month, -add_month)
>>> month_add(2015, 7, 1)
(2015, 8)
>>> month_add(2015, 7, 20)
(2017, 3)
>>> month_add(2015, 7, 12)
(2016, 7)
>>> month_add(2015, 7, 24)
(2017, 7)
>>> month_add(2015, 7, -2)
(2015, 5)
>>> month_add(2015, 7, -12)
(2014, 7)
>>> month_add(2015, 7, -13)
(2014, 6)
example using the time object:
start_time = time.gmtime(time.time()) # start now
#increment one month
start_time = time.gmtime(time.mktime([start_time.tm_year, start_time.tm_mon+1, start_time.tm_mday, start_time.tm_hour, start_time.tm_min, start_time.tm_sec, 0, 0, 0]))
My very simple solution, which doesn't require any additional modules:
def addmonth(date):
if date.day < 20:
date2 = date+timedelta(32)
else :
date2 = date+timedelta(25)
date2.replace(date2.year, date2.month, day)
return date2
If I want to add 100 years in my program, why is it showing the wrong date?
import datetime
stringDate= "January 10, 1920"
dateObject= datetime.datetime.strptime(stringDate, "%B %d, %Y")
endDate= dateObject+datetime.timedelta(days=100*365)
print dateObject.date()
print endDate.date()
The number of seconds in a year is not fixed. Think you know how many days are in a year? Think again.
To perform period (calendar) arithmetic, you could use dateutil.relativedelta:
#!/usr/bin/env python
from datetime import date
from dateutil.relativedelta import relativedelta # $ pip install python-dateutil
print(date(1920, 1, 10) + relativedelta(years=+100))
# -> 2020-01-10
To understand, why d.replace(year=d.year + 100) fails, consider:
print(date(2000, 2, 29) + relativedelta(years=+100))
2100-02-28
Notice that 2100 is not a leap year while 2000 is a leap year.
If the only units you want to add is year then you could implement it using only stdlib:
from calendar import isleap
def add_years(d, years):
new_year = d.year + years
try:
return d.replace(year=new_year)
except ValueError:
if (d.month == 2 and d.day == 29 and # leap day
isleap(d.year) and not isleap(new_year)):
return d.replace(year=new_year, day=28)
raise
Example:
from datetime import date
print(add_years(date(1920, 1, 10), 100))
# -> 2020-01-10
print(add_years(date(2000, 2, 29), 100))
# -> 2100-02-28
print(add_years(date(2000, 2, 29), 4))
# -> 2004-02-29
You can't just add 100 * 365 days, because there are leap years with 366 days in that timespan. Over your 100 year span you are missing 25 days.
Better to just use the datetime.replace() method here:
endDate = dateObject.replace(year=dateObject.year + 100)
This can still fail for February 29th in a leap year, as depending on the number of years you add you'd end up with an invalid date. You could move back to February 28th in that case, or use March 31st; handle the exception thrown and switch to your chosen replacement:
years = 100
try:
endDate = dateObject.replace(year=dateObject.year + years)
except ValueError::
# Leap day in a leap year, move date to February 28th
endDate = dateObject.replace(year=dateObject.year + years, day=28)
Demo:
>>> import datetime
>>> dateObject = datetime.datetime(1920, 1, 10, 0, 0)
>>> dateObject.replace(year=dateObject.year + 100)
datetime.datetime(2020, 1, 10, 0, 0)
man 3 mktime
Anyone who ever did C knows the answer.
mktime automatically adds overflowing values to the next bigger unit. You just need to convert it back to a datetime.
For example you can feed it with 2019-07-40, which converts to 2019-08-09.
>>> datetime.fromtimestamp(mktime((2019, 7, 40, 0, 0, 0, 0, 0, 0)))
datetime.datetime(2019, 8, 9, 0, 0)
Or 2019-03-(-1) is converted to 2019-02-27:
>>> datetime.fromtimestamp(mktime((2019, 3, -1, 0, 0, 0, 0, 0, 0)))
datetime.datetime(2019, 2, 27, 0, 0)
So you just take your old date and add whatever you like:
now = datetime.datetime.now()
hundred_days_later = datetime.datetime.fromtimestamp(mktime((now.year, now.month, now.day + 100, now.hour, now.minute, now.second, 0, 0, 0)))
For the past 5 years, I've been using pandas Timestamp and Timedelta for everything date related.
For example, to add 3 years to any date in string format:
date = "2003-07-01"
date_start = Timestamp(date)
date_end = Timestamp(date_start.year+3, date_start.month, date_start.day)
date_end
# Out:
Timestamp('2006-07-01 00:00:00')
To add 40 days to a date, use Timedelta (it does not support years, or else we could have used it for the last problem):
date_end = date_start + Timedelta(40, unit="days")
date_end
# Out:
Timestamp('2003-08-10 00:00:00')
With python I want to calculate the delta days of a day_of_a_year day and its corresponding month, as well delta days for month + 1.
*Sorry I forgot to mention that the year is a known variable
eg.
def a(day_of_year):
<...>
return [(days_from_start_of_month),(days_untill_end_of_month)]
so
If
day_of_year = 32
a(32) = (2,28) #assuming the month which the day_of_year corresponds to starts from day 30 and ends to day 60.
So far im studying the datetime , timeutils and calendar modules and I really can't figure out the logic for the code! I wish i had something solid to show, but Im getting lost somewhere in timedelta functions.
The first day of the month is easy to construct, as is the first day of the next month. Once you have those, the rest is even easier. As pointed out by the OP, the calendar.monthrange function gives us the most readable method to get the last day of a month.
>>> from datetime import date, year
>>> import calendar
>>> def first_day(dt):
... # Simply copy year and month into new date instance
... return date(dt.year, dt.month, 1)
...
>>> def last_day(dt):
... days_in_month = calendar.monthrange(dt.year, dt.month)[1]
... return date(dt.year, dt.month, days_in_month)
...
>>> nth_day = 32
>>> day_of_year = date(2012, 1, 1) + timedelta(days=nth_day - 1)
>>> day_of_year
datetime.date(2012, 2, 1)
>>> first_day(day_of_year), last_day(day_of_year)
(datetime.date(2012, 2, 1), datetime.date(2012, 2, 29))
>>> day_of_year - first_day(day_of_year), last_day(day_of_year) - day_of_year
(datetime.timedelta(0), datetime.timedelta(28))
To combine these techniques into one function:
def delta_to_start_and_end(year, day_of_year):
dt = date(year, 1, 1) + timedelta(days=(day_of_year - 1))
def first_day(dt):
return date(dt.year, dt.month, 1)
def last_day(dt):
days_in_month = calendar.monthrange(dt.year, dt.month)[1]
return date(dt.year, dt.month, days_in_month)
return (dt - first_day(dt)).days, (last_day(dt) - dt).days
Output:
>>> delta_to_start_and_end(2012, 32)
(0, 28)
>>> delta_to_start_and_end(2011, 32)
(0, 27)
>>> delta_to_start_and_end(2012, 34)
(2, 26)
>>> delta_to_start_and_end(2012, 364)
(28, 2)
I'm not sure if you want to add 1 to each of these two values; currently the first day of the month (first example) gives you 0 as the first value and (days-in-the-month - 1) as the second value, as this is the difference in days from those points. It's trivial to add + 1 twice on the last line of the delta_to_start_and_end function if you need these.
As a historic note, a previous version of this answer used a different method to calculate the last day of a month without the calendar module:
def last_day(dt):
rest, month = divmod(dt.month, 12)
return date(dt.year + rest, month + 1, 1) - timedelta(days=1)
This function uses the divmod builtin function to handle the 'current month is December' edge-case; in that case the next month is not 13, but 1 and we'd need to increase the year by one as well. Rolling over a number back to the 'start' is the modulus of the number, but the divmod function gives us the divisor as well, which happens to be 1 if the current month is 12. This gives us a handy indicator when to increase the year.
I don't think that there's an existing library that works for this. You have to make something yourself, like this:
monthdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
day = 32
total = 0
for i in monthdays:
if day - total - i < 0:
before = day - total
after = total + i - day
break
total += i
print before, after
(just a quick start, there is possibly a more elegant way)
Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?
Given an instance x of datetime.date, (x.month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).
Originally two answers, multiply upvoted and even originally accepted (both currently deleted), were buggy -- not doing the -1 before the division, and dividing by 4 instead of 3. Since .month goes 1 to 12, it's easy to check for yourself what formula is right:
for m in range(1, 13):
print m//4 + 1,
print
gives 1 1 1 2 2 2 2 3 3 3 3 4 -- two four-month quarters and a single-month one (eep).
for m in range(1, 13):
print (m-1)//3 + 1,
print
gives 1 1 1 2 2 2 3 3 3 4 4 4 -- now doesn't this look vastly preferable to you?-)
This proves that the question is well warranted, I think;-).
I don't think the datetime module should necessarily have every possible useful calendric function, but I do know I maintain a (well-tested;-) datetools module for the use of my (and others') projects at work, which has many little functions to perform all of these calendric computations -- some are complex, some simple, but there's no reason to do the work over and over (even simple work) or risk bugs in such computations;-).
IF you are already using pandas, it's quite simple.
import datetime as dt
import pandas as pd
quarter = pd.Timestamp(dt.date(2016, 2, 29)).quarter
assert quarter == 1
If you have a date column in a dataframe, you can easily create a new quarter column:
df['quarter'] = df['date'].dt.quarter
I would suggest another arguably cleaner solution. If X is a datetime.datetime.now() instance, then the quarter is:
import math
Q=math.ceil(X.month/3.)
ceil has to be imported from math module as it can't be accessed directly.
For anyone trying to get the quarter of the fiscal year, which may differ from the calendar year, I wrote a Python module to do just this.
Installation is simple. Just run:
$ pip install fiscalyear
There are no dependencies, and fiscalyear should work for both Python 2 and 3.
It's basically a wrapper around the built-in datetime module, so any datetime commands you are already familiar with will work. Here's a demo:
>>> from fiscalyear import *
>>> a = FiscalDate.today()
>>> a
FiscalDate(2017, 5, 6)
>>> a.fiscal_year
2017
>>> a.quarter
3
>>> b = FiscalYear(2017)
>>> b.start
FiscalDateTime(2016, 10, 1, 0, 0)
>>> b.end
FiscalDateTime(2017, 9, 30, 23, 59, 59)
>>> b.q3
FiscalQuarter(2017, 3)
>>> b.q3.start
FiscalDateTime(2017, 4, 1, 0, 0)
>>> b.q3.end
FiscalDateTime(2017, 6, 30, 23, 59, 59)
fiscalyear is hosted on GitHub and PyPI. Documentation can be found at Read the Docs. If you're looking for any features that it doesn't currently have, let me know!
This is very simple and works in python3:
from datetime import datetime
# Get current date-time.
now = datetime.now()
# Determine which quarter of the year is now. Returns q1, q2, q3 or q4.
quarter_of_the_year = f'q{(now.month-1)//3+1}'
if m is the month number...
import math
math.ceil(float(m) / 3)
This method works for any mapping:
month2quarter = {
1:1,2:1,3:1,
4:2,5:2,6:2,
7:3,8:3,9:3,
10:4,11:4,12:4,
}.get
We have just generated a function int->int
month2quarter(9) # returns 3
This method is also fool-proof
month2quarter(-1) # returns None
month2quarter('July') # returns None
Here is an example of a function that gets a datetime.datetime object and returns a unique string for each quarter:
from datetime import datetime, timedelta
def get_quarter(d):
return "Q%d_%d" % (math.ceil(d.month/3), d.year)
d = datetime.now()
print(d.strftime("%Y-%m-%d"), get_q(d))
d2 = d - timedelta(90)
print(d2.strftime("%Y-%m-%d"), get_q(d2))
d3 = d - timedelta(180 + 365)
print(d3.strftime("%Y-%m-%d"), get_q(d3))
And the output is:
2019-02-14 Q1_2019
2018-11-16 Q4_2018
2017-08-18 Q3_2017
For those, who are looking for financial year quarter data,
using pandas,
import datetime
import pandas as pd
today_date = datetime.date.today()
quarter = pd.PeriodIndex(today_date, freq='Q-MAR').strftime('Q%q')
reference:
pandas period index
This is an old question but still worthy of discussion.
Here is my solution, using the excellent dateutil module.
from dateutil import rrule,relativedelta
year = this_date.year
quarters = rrule.rrule(rrule.MONTHLY,
bymonth=(1,4,7,10),
bysetpos=-1,
dtstart=datetime.datetime(year,1,1),
count=8)
first_day = quarters.before(this_date)
last_day = (quarters.after(this_date)
-relativedelta.relativedelta(days=1)
So first_day is the first day of the quarter, and last_day is the last day of the quarter (calculated by finding the first day of the next quarter, minus one day).
I tried the solution with x//3+1 and x//4+1,
We get incorrect quarter in either case.
The correct answer is like this
for i in range(1,13):
print(((i-1)//3)+1)
import datetime
def get_quarter_number_and_date_from_choices(p_quarter_choice):
"""
:param p_quarter_choice:
:return:
"""
current_date = datetime.date.today()
# current_quarter = current_date.month - 1 // 3 + 1
if p_quarter_choice == 'Q1':
quarter = 1
q_start_date = datetime.datetime(current_date.year, 3 * quarter - 2, 1)
q_end_date = datetime.datetime(current_date.year, 3 * quarter + 1, 1) + datetime.timedelta(days=-1)
return q_start_date, q_end_date
elif p_quarter_choice == 'Q2':
quarter = 2
q_start_date = datetime.datetime(current_date.year, 3 * quarter - 2, 1)
q_end_date = datetime.datetime(current_date.year, 3 * quarter + 1, 1) + datetime.timedelta(days=-1)
return q_start_date, q_end_date
elif p_quarter_choice == 'Q3':
quarter = 3
q_start_date = datetime.datetime(current_date.year, 3 * quarter - 2, 1)
q_end_date = datetime.datetime(current_date.year, 3 * quarter + 1, 1) + datetime.timedelta(days=-1)
return q_start_date, q_end_date
elif p_quarter_choice == 'Q4':
quarter = 4
q_start_date = datetime.datetime(current_date.year, 3 * quarter - 2, 1)
q_end_date = datetime.datetime(current_date.year, 3 * quarter, 1) + datetime.timedelta(days=30)
return q_start_date, q_end_date
return None
hmmm so calculations can go wrong, here is a better version (just for the sake of it)
first, second, third, fourth=1,2,3,4# you can make strings if you wish :)
quarterMap = {}
quarterMap.update(dict(zip((1,2,3),(first,)*3)))
quarterMap.update(dict(zip((4,5,6),(second,)*3)))
quarterMap.update(dict(zip((7,8,9),(third,)*3)))
quarterMap.update(dict(zip((10,11,12),(fourth,)*3)))
print quarterMap[6]
Here is a verbose, but also readable solution that will work for datetime and date instances
def get_quarter(date):
for months, quarter in [
([1, 2, 3], 1),
([4, 5, 6], 2),
([7, 8, 9], 3),
([10, 11, 12], 4)
]:
if date.month in months:
return quarter
using dictionaries, you can pull this off by
def get_quarter(month):
quarter_dictionary = {
"Q1" : [1,2,3],
"Q2" : [4,5,6],
"Q3" : [7,8,9],
"Q4" : [10,11,12]
}
for key,values in quarter_dictionary.items():
for value in values:
if value == month:
return key
print(get_quarter(3))
for m in range(1, 13):
print ((m*3)//10)
A revisited solution using #Alex Martelli formula and creting a quick function as the question asks.
from datetime import timedelta, date
date_from = date(2021, 1, 1)
date_to = date(2021, 12, 31)
get_quarter = lambda dt: (dt.month-1)//3 + 1
quarter_from = get_quarter(date_from)
quarter_to = get_quarter(date_to)
print(quarter_from)
print(quarter_to)
# 1
# 4
def euclid(a,b):
r = a % b
q = int( ( (a + b - 1) - (a - 1) % b ) / b )
return(q,r)
months_per_year = 12
months_per_quarter = 3
for i in range(months_per_year):
print(i+1,euclid(i+1,months_per_quarter)[0])
#1 1
#2 1
#3 1
#4 2
#5 2
#6 2
#7 3
#8 3
#9 3
#10 4
#11 4
#12 4