10

私は現在、ユーザーがオプションで日付範囲を指定できるようにするレポートコードを書いています。それが機能する(簡略化された)方法は次のとおりです。

  • ユーザーは(オプションで)年を指定します。
  • ユーザーは(オプションで)月を指定します。
  • ユーザーは(オプションで)日を指定します。

これがコードスニペットと、私がやりたいことを説明するコメントです

from datetime import datetime, timedelta

# ...

now = datetime.now()
start_time = now.replace(hour=0, minute=0, second=0, microsecond=0)
stop_time = now
# If the user enters no year, month, or day--then we'll simply run a
# report that only spans the current day (from the start of today to now).

if options['year']:
    start_time = start_time.replace(year=options['year'], month=0, day=0)
    stop_time = stop_time.replace(year=options['year'])
    # If the user specifies a year value, we should set stop_time to the last
    # day / minute / hour / second / microsecond of the year, that way we'll
    # only generate reports from the start of the specified year, to the end
    # of the specified year.

if options['month']:
    start_time = start_time.replace(month=options['month'], day=0)
    stop_time = stop_time.replace(month=options['month'])
    # If the user specifies a month value, then set stop_time to the last
    # day / minute / hour / second / microsecond of the specified month, that
    # way we'll only generate reports for the specified month.

if options['day']:
    start_time = start_time.replace(day=options['day'])
    stop_time = stop_time.replace(day=options['day'])
    # If the user specifies a day value, then set stop_time to the last moment of
    # the current day, so that reports ONLY run on the current day.

私は上記のコードを書くための最もエレガントな方法を見つけようとしています-私はtimedeltaでそれを行う方法を見つけようとしていますが、それを理解できないようです。何かアドバイスをいただければ幸いです。

4

6 に答える 6

5

を使用dict.getすると、コードを簡略化できます。datetime.replaceオブジェクトとtimedeltaオブジェクトを使用するよりも少しクリーンです。

これがあなたが始めるための何かです:

from datetime import datetime

options = dict(month=5, day=20)
now = datetime.now()
start_time = datetime(year=options.get('year', now.year), 
                      month=options.get('month', 1),
                      day=options.get('day', 1)
                      hour=0,
                      minute=0,
                      second=0)
stop_time =  datetime(year=options.get('year', now.year), 
                      month=options.get('month', now.month),
                      day=options.get('day', now.day),
                      hour=now.hour,
                      minute=now.minute,
                      second=now.second)
于 2011-11-02T18:57:42.157 に答える
4

を設定するには、必要に応じて1年、1か月、または1日stop_time進めてから、1を引きます。start_timetimedelta(microseconds=1)

if options['year']:
    start_time = start_time.replace(year=options['year'], month=1, day=1)
    stop_time = stop_time.replace(year=options['year']+1)-timedelta(microseconds=1)

elif options['month']:
    start_time = start_time.replace(month=options['month'], day=1)
    months=options['month']%12+1
    stop_time = stop_time.replace(month=months,day=1)-timedelta(microseconds=1)

else:
    start_time = start_time.replace(day=options['day'])
    stop_time = stop_time.replace(day=options['day'])+timedelta(days=1,microseconds=-1)
于 2011-11-02T19:02:19.973 に答える
3
    today = datetime.date.today()
    begintime = today.strftime("%Y-%m-%d 00:00:00")
    endtime = today.strftime("%Y-%m-%d 23:59:59")
于 2016-09-12T08:25:40.690 に答える
0
from datetime import datetime, date, timedelta

def get_current_timestamp():
    return int(datetime.now().timestamp())

def get_end_today_timestamp():
    # get 23:59:59
    result = datetime.combine(date.today() + timedelta(days=1), datetime.min.time())
    return int(result.timestamp()) - 1

def get_datetime_from_timestamp(timestamp):
    return datetime.fromtimestamp(timestamp)

end_today = get_datetime_from_timestamp(get_end_today_timestamp())
于 2019-12-10T06:20:55.017 に答える
0
date = datetime.strftime('<input date str>')

date.replace(hour=0, minute=0, second=0, microsecond=0)  # now we get begin of the day
date += timedelta(days=1, microseconds=-1)  # now end of the day
于 2020-07-06T03:28:54.113 に答える
0

ここでいくつかの答えを見て、実際には非常にエレガントなものを見つけられなかった後、私は標準ライブラリを少し調べて、現在の解決策を見つけました(私は非常に気に入っています)dateutil:。

これが私がそれを実装した方法です:

from datetime import date
from dateutil.relativedelta import relativedelta

now = date.today()
stop_time = now + relativedelta(days=1)
start_time = date(
    # NOTE: I'm not doing dict.get() since in my implementation, these dict
    # keys are guaranteed to exist.
    year = options['year'] or now.year,
    month = options['month'] or now.month,
    day = options['day'] or now.day
)

if options['year']:
    start_time = date(year=options['year'] or now.year, month=1, day=1)
    stop_time = start_time + relativedelta(years=1)

if options['month']:
    start_time = date(
        year = options['year'] or now.year,
        month = options['month'] or now.month,
        day = 1
    )
    stop_time = start_time + relativedelta(months=1)

if options['day']:
    start_time = date(
        year = options['year'] or now.year,
        month = options['month'] or now.month,
        day = options['day'] or now.day,
    )
    stop_time = start_time + relativedelta(days=1)

# ... do stuff with start_time and stop_time here ...

この実装で私が気に入っているのは、Pythondateutil.relativedata.relativedataがエッジケースで非常にうまく機能することです。日/月/年が正しくなります。を持っている場合はmonth=12relativedata(months=1)年をインクリメントして月を1に設定します(うまく機能します)。

また、上記の実装では、ユーザーがオプションの日付(年、月、日)を指定しなかった場合、適切なデフォルト(start_time =今朝、stop_time =今夜)にフォールバックします。デフォルトでは、当日の作業のみを行います。

みんなの答えに感謝します-彼らは私の研究に役立ちました。

于 2020-09-27T05:15:13.580 に答える