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

前端 未结 6 1546
无人及你
无人及你 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 11:19

    Using dict.get can simplify your code. It is a bit cleaner than using datetime.replace and timedelta objects.

    Here's something to get you started:

    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)
    

提交回复
热议问题