How to get quarter beginning date in python

Viewed 4007

I want to get date beginning of quarter of the date

x="2018-02-07"
x=pd.to_datetime(x)
x=x-pd.offsets.QuarterBegin()
print(x)
2017-12-01 00:00:00

Which is wrong and should be "2018-01-01 00:00:00"

Can somebody help me where I am going wrong?

3 Answers

You can convert to a period and then to a timestamp:

x = pd.to_datetime('2018-02-07')

res = x.to_period('Q').to_timestamp()

print(res)

Timestamp('2018-01-01 00:00:00')

In core Python without depending on Pandas:

from datetime import date


x = date.fromisoformat('2018-02-07')
x_qtr = date(x.year, 3 * ((x.month - 1) // 3) + 1, 1)

print(x_qtr)
# 2018-01-01
pd.to_datetime("2018-02-07") - pd.tseries.offsets.BQuarterBegin(startingMonth=1)
Related