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.replacetimedelta对象要干净一些。

这里有一些东西可以帮助你开始:

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

要设置stop_time,根据需要提前start_time一年、一个月或一天,然后减一timedelta(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

在查看了这里的一些答案之后,并没有真正找到任何非常优雅的东西,我在标准库中做了一些探索,并找到了我当前的解决方案(我非常喜欢)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=12,并且做relativedata(months=1),它会增加年份并将月份设置为 1(效果很好)。

另外:在上面的实现中,如果用户没有指定任何可选日期(年、月或日)——我们将回退到一个不错的默认值(start_time = 今天早上,stop_time = 今晚),这样我们就会默认只做当天的事情。

感谢大家的回答——他们对我的研究很有帮助。

于 2020-09-27T05:15:13.580 回答
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 回答