전월의 파이썬 날짜


131

파이썬으로 지난 달의 날짜를 얻으려고합니다. 내가 시도한 것은 다음과 같습니다.

str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )

그러나이 방법은 두 가지 이유로 나쁩니다. 먼저 2012 년 2 월 (201202 대신)에 20122를 반환하고 두 번째로 1 월에 12 대신 12 대신 0을 반환합니다.

나는이 문제를 bash에서 해결했다.

echo $(date -d"3 month ago" "+%G%m%d")

bash 가이 목적을 위해 내장 된 방법을 가지고 있다면 훨씬 더 많은 파이썬 이이 목표를 달성하기 위해 자신의 스크립트를 작성하는 것보다 더 나은 것을 제공해야한다고 생각합니다. 물론 나는 다음과 같은 것을 할 수있다 :

if int(time.strftime('%m')) == 1:
    return '12'
else:
    if int(time.strftime('%m')) < 10:
        return '0'+str(time.strftime('%m')-1)
    else:
        return str(time.strftime('%m') -1)

이 코드를 테스트하지 않았으며 어쨌든 사용하고 싶지 않습니다 (다른 방법을 찾을 수 없다면 : /)

당신의 도움을 주셔서 감사합니다!


답변:


299

datetime 및 datetime.timedelta 클래스는 친구입니다.

  1. 오늘 찾으십시오.
  2. 이것을 사용하여 이번 달의 첫날을 찾으십시오.
  3. timedelta를 사용하여 하루 전날의 마지막 날까지 백업하십시오.
  4. 찾고있는 YYYYMM 문자열을 인쇄하십시오.

이처럼 :

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 lastMonth = first - datetime.timedelta(days=1)
 print(lastMonth.strftime("%Y%m"))

201202 인쇄됩니다.


31
당신은 .replace()방법을 사용할 수 있습니다 :datetime.utcnow().replace(day=1) - timedelta(days=1)
jfs

1
멋있는! 교체 방법을 놓쳤습니다.
bgporter

.replace()기능을 연결할 수도 있습니다. 지난 달에 한 번 한 다음 다시 원하는 일을 얻으십시오. 첫번째 : d = date.today() 그때one_month_ago = (d.replace(day=1) - timedelta(days=1)).replace(day=d.day)
Thane Plummer

@JFSebastian 당신이 맞습니다. 지적 해 주셔서 감사합니다. "달"이 일정한 시간이 아니기 때문에 이것에 대한 우아한 하나의 라이너가없는 것 같습니다. 2nd 의 함수에서 더 많은 추악함 을 가져 calendar오고 사용하여 추악한 일을 할 수는 있지만 피닉스적인 것처럼 보이지 않으며 코너 사례를 설명하지 않습니다. 알고리즘의 일부로 예외를 사용하는 것을 싫어하지만 모든 경우에 대해 어떤 계정을 사용하여 아래 답변을 업데이트했습니다 . calendar.mdays[d.month-1]min()replacetry - except
Thane Plummer

이반의 대답을보고, 추가 분 (. date.today () 일, last_day_of_previous_month.day)
michel.iamit

70

dateutil을 사용해야합니다 . 그것으로, 당신은 relativedelta를 사용할 수 있습니다, 그것은 timedelta의 개선 된 버전입니다.

>>> import datetime 
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relativedelta(months=-1)
2012-02-15 12:33:04.281248

첫 번째 달에는 작동하지 않습니다. >>> IllegalMonthError : bad month number -1; 1-12 세 여야합니다
mtoloo

@mtoloo 어떤 버전의 dateutil? 나는 그 문제가 없지만 다른 대안을 추가 할 것이다
Dave Butler

1
@bgporter는 매우 훌륭한 솔루션을 가지고 있지만 그의 솔루션은 다음 달을 찾는 데 좋지 않습니다.
Daniel F

3
@mtoloo 당신은 아마 달 / 월을 잘못 타자했을 것입니다
r_black

2
@r_black 예 당신이 맞아요. 그건 내 잘못이야 여기에 제공된 해결책은 정확하며 해당 연도의 첫 달에는 추가 점검이 필요하지 않습니다.
mtoloo

45
from datetime import date, timedelta

first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)

print "Previous month:", last_day_of_previous_month.month

또는:

from datetime import date, timedelta

prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month

솔루션의 일부 .... 지난 달의 일을 찾으려면 day_previous_month = min (today.day, last_day_of_previous_month.day)와 같이 일 수를 초과하지 않도록하십시오.
michel.iamit 2018

9

바탕 bgporter의 대답 .

def prev_month_range(when = None): 
    """Return (previous month's start date, previous month's end date)."""
    if not when:
        # Default to today.
        when = datetime.datetime.today()
    # Find previous month: https://stackoverflow.com/a/9725093/564514
    # Find today.
    first = datetime.date(day=1, month=when.month, year=when.year)
    # Use that to find the first day of this month.
    prev_month_end = first - datetime.timedelta(days=1)
    prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
    # Return previous month's start and end dates in YY-MM-DD format.
    return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))

5

매우 쉽고 간단합니다. 이 작업을 수행

from dateutil.relativedelta import relativedelta
from datetime import datetime

today_date = datetime.today()
print "todays date time: %s" %today_date

one_month_ago = today_date - relativedelta(months=1)
print "one month ago date time: %s" % one_month_ago
print "one month ago date: %s" % one_month_ago.date()

출력은 다음과 같습니다. $ python2.7 main.py

todays date time: 2016-09-06 02:13:01.937121
one month ago date time: 2016-08-06 02:13:01.937121
one month ago date: 2016-08-06

4

여기에 와서 지난 달의 첫날과 마지막 날을 모두 찾는 사람에게 :

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)

start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)

# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)

산출:

First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28

한 달의 시작과 끝을 얻을 수 (등) 할 경우, 한 번 봐 가지고 Calendar: 모듈 stackabuse.com/introduction-to-the-python-calendar-module
toast38coza

우리가 두 번째 이전 달을 시작하고 끝내려면?
게이머

3
def prev_month(date=datetime.datetime.today()):
    if date.month == 1:
        return date.replace(month=12,year=date.year-1)
    else:
        try:
            return date.replace(month=date.month-1)
        except ValueError:
            return prev_month(date=date.replace(day=date.day-1))

3 월 31 일
마이크

1

재미로, divmod를 사용한 순수한 수학 답변. 곱셈으로 인해 매우 비효율적이며 월 수를 간단히 확인할 수 있습니다 (12와 같거나 연도 증가 등).

year = today.year
month = today.month

nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
    nm[1] = 12
    nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
    pm[1] = 12
    pm[0] -= 1

next_month = nm
previous_month = pm

1

진자 매우 완벽한 라이브러리를 사용하면 다음과 같은 subtract방법이 있습니다 ( "subStract"아님).

import pendulum
today = pendulum.datetime.today()  # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'

우리는 그것이 점프 년을 다루는 것을 본다.

반대의 값은 add입니다.

https://pendulum.eustace.io/docs/#addition-and-subtraction


0

@JF Sebastian의 의견을 바탕으로 replace()함수를 연결하여 "달"로 되돌아 갈 수 있습니다 . 한 달은 일정한 시간이 아니기 때문에이 솔루션은 이전 달의 같은 날짜로 돌아 가려고하지만 모든 달에 작동하지는 않습니다. 이 경우이 알고리즘의 기본값은 전월의 마지막 날입니다.

from datetime import datetime, timedelta

d = datetime(2012, 3, 31) # A problem date as an example

# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
    # try to go back to same day last month
    one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
    pass
print("one_month_ago: {0}".format(one_month_ago))

산출:

one_month_ago: 2012-02-29 00:00:00

0

LINUX / UNIX 환경에서 EXE 유형 파일의 ASCII 문자를 보려면 "od -c 'filename'| more"

인식 할 수없는 항목이 많이있을 수 있지만 모두 표시되고 HEX 표현이 표시되며 ASCII 해당 문자 (적절한 경우)가 16 진 코드 행을 따릅니다. 알고있는 컴파일 된 코드에서 시도하십시오. 당신은 당신이 인식하는 것들을 볼 수 있습니다.


질문에 어떻게 대답하는지 설명하기 위해 이것을 편집 할 수 있습니까?
AdrianHHH 2016 년

0

dateparser주어진 자연 언어의 과거 날짜를 결정하고 해당 Python datetime객체를 반환 할 수 있는 고급 라이브러리 가 있습니다.

from dateparser import parse
parse('4 months ago')
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.