B
B
Brodyachiykot2022-01-20 02:07:09
Python
Brodyachiykot, 2022-01-20 02:07:09

How to make the year and month change in Python Datetime?

Hello, I have a problem with the date and time. I need to make sure that the payment is made on the specified day, but the year and month change.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2022-01-20
@trapwalker

You can pick up one of the good powerful libraries for convenient work with dante, so that there are methods for flipping through dates by month.
But if you don’t want to produce dependencies, then I recommend that you regularly parse the date into a day, month, and year, make sure that the day does not exceed 28 (otherwise, such a number cannot be found in every month), and then add 1 modulo 12 to the month. overflow needs to be increased by another year.
This is elegantly written using the divmod function:

month -= 1
year_increment, month = divmod(month + 1, 12)
month += 1

D
dmshar, 2022-01-20
@dmshar

If you are working with Pandas then there is an easier solution.
Add the given number of months (in this case -6)

import datetime as dt
import pandas as pd
date = dt.date.today() + pd.offsets.DateOffset(months=6)
print(date)

Result: Add a year:
2022-07-20 00:00:00
date = dt.date.today() + pd.offsets.DateOffset(years=1)
print(date)

Result: Add both:
2023-01-20 00:00:00
date = dt.date.today() + pd.offsets.DateOffset(years=1,months=3)
print(date)

Result:
2023-04-20 00:00:00

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question