What's the most elegant way to get the end of the day (datetime)?

前端 未结 6 1539
无人及你
无人及你 2021-02-14 10:16

I\'m currently writing some reporting code that allows users to optionally specify a date range. The way it works (simplified), is:

  • A user (optionally) specifies a
6条回答
  •  情深已故
    2021-02-14 10:58

    To set the stop_time, advance start_time one year, month or day as appropriate, then subtract one 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)
    

提交回复
热议问题