Programing

지난달의 파이썬 날짜

lottogame 2020. 8. 12. 22:07
반응형

지난달의 파이썬 날짜


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

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

그러나이 방법은 두 가지 이유로 좋지 않습니다. 먼저 201202 대신 2012 년 2 월에 20122를 반환하고, 두 번째로 1 월에 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)

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

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


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
 >>>

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

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

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'))

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))

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

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

여기에 와서 지난 달의 첫날과 마지막 날을 모두 얻으려는 사람의 경우 :

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

재미로 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

Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

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))

Output:

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

If you want to look at the ASCII letters in a EXE type file in a LINUX/UNIX Environment, try "od -c 'filename' |more"

You will likely get a lot of unrecognizable items, but they will all be presented, and the HEX representations will be displayed, and the ASCII equivalent characters (if appropriate) will follow the line of hex codes. Try it on a compiled piece of code that you know. You might see things in it you recognize.


This worked for me:

import datetime
today = datetime.date.today()
last_month = today.replace(month=today.month-1, day=1)

참고URL : https://stackoverflow.com/questions/9724906/python-date-of-the-previous-month

반응형