Python Timedelta 월을 사용하여 날짜 계산

Haider Ali 2023년6월21일
  1. 파이썬 datetime 함수
  2. relativedelta()를 사용하여 Python을 사용하여 날짜 계산
Python Timedelta 월을 사용하여 날짜 계산

이 가이드에서는 timedelta를 사용하여 Python에서 datetime을 사용하는 방법을 배웁니다. 현재 날짜 또는 다른 날짜로부터 6개월 날짜를 계산하는 방법을 살펴보겠습니다.

다이빙하자!

파이썬 datetime 함수

음, 먼저 datetime 기능이 작동하는 방식과 기능을 제한하는 단점이 무엇인지 살펴보겠습니다. 가장 먼저 알아야 할 것은 코드에서 datetime을 가져오는 것입니다.

import datetime

그런 다음 datetime의 인스턴스를 생성합니다. 인스턴스를 만든 후에는 해당 산술 함수를 사용할 수 있습니다.

하루와 한 달을 뺄 수 있습니다. 다음 코드를 살펴보십시오.

# instance of datetime
date = datetime.datetime(2022, 2, 1)
# subtracting 1 from the month
date = date.replace(month=date.month - 1)
print(date)

출력:

2022-01-01 00:00:00

위의 코드에서 볼 수 있듯이 산술 함수를 사용하여 이전에 설정한 날짜에서 한 달을 뺍니다. 하지만 여기에 문제가 있습니다. 위의 결과에서 한 달을 빼려고 하면 어떻게 될까요?

코드는 우리에게 오류를 줄 것입니다. 구경하다.

date = date.replace(month=date.month - 1)

출력:

    date = date.replace(month=date.month-1)
ValueError: month must be in 1..12

datetime 함수는 지원하지 않기 때문에 산술 함수를 사용하고 전체 연도를 빼는 것을 허용하지 않습니다. 마찬가지로 현재 날짜가 12월 말일에 1 또는 2를 더하면 같은 오류가 발생합니다.

# if you add 1 in date, it will throw an error because it doesn't support it
date = datetime.datetime(2022, 12, 1)
date_ = date.replace(month=date_1.month + 1)

출력:

    date = date.replace(month=date.month+1)
ValueError: month must be in 1..12

다시 질문으로 돌아가서 현재 날짜 또는 다른 날짜로부터 6개월 날짜를 어떻게 계산할 수 있습니까? 답은 relativedelta를 사용하는 데 있습니다.

relativedelta()를 사용하여 Python을 사용하여 날짜 계산

Python 코드에서 relativedelta를 사용하기 전에 dateutil을 설치하여 relativedelta를 가져와야 합니다. 명령 프롬프트에서 다음을 실행하여 dateutil을 설치합니다.

pip install python-dateutil

일단 설치되면 여기에서 relativedelta를 가져와야 합니다.

from dateutil import relativedelta

그런 다음 datetimerelativedelta를 모두 사용하여 현재 문제를 해결해야 합니다. 다음 코드를 살펴보십시오.

date = datetime.datetime(2022, 1, 1)
# created the instance of the datetime and set the current date as 2022,1,1

이제 relativedelta의 인스턴스를 생성하고 월 값을 1로 설정합니다.

r_date = relativedelta.relativedelta(months=1)

이제 datetime 인스턴스에서 relativedelta 인스턴스를 빼기만 하면 됩니다. 그것은 우리가 원하는 답을 줄 것입니다.

# if you subtract the relativedelta variable with the date instance, it will work correctly and change the year too.
new_date = date - r_date
print(new_date)

출력:

2021-12-01 00:00:00

마찬가지로 날짜에 1을 더하면 원하는 결과를 얻을 수 있습니다.

이제 이 기술을 사용하여 현재 날짜에서 날짜를 계산할 수 있습니다. 현재 날짜로부터 6개월의 날짜를 계산하는 방법에 대한 답변입니다.

작가: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

관련 문장 - Python Date