How do I get the Python UTC datetime in which hours, minutes, and seconds are all zeroes?

I'm using Python 3.8. Is there a simpler way to get the current UTC time in which the hour, minute, and second are all zero? For example, if UTC now evalutes to "2020-09-24 12:34:45", I would want my result to be "2020-09-24 00:00:00". Right now I have

today = datetime.datetime.utcnow()
today_wo_time_str = datetime.datetime.strftime(today, '%Y-%m-%d 00:00:00')
today_wo_time_obj = datetime.datetime.stpftime(today_wo_time_str, '%Y-%m-%d 00:00:00')

which seems a little unecessarily wordy.

1 answer

  • answered 2020-09-24 15:42 Tim Biegeleisen

    One option would be get the current UTC datetime, as you are already doing, and then combine its date only component with a midnight time component, using the combine() function.

    import datetime
    
    utc_now = datetime.datetime.utcnow()
    midnight = datetime.time(0)
    utc_midnight = datetime.datetime.combine(utc_now.date(), midnight)
    print(utc_midnight)
    

    This prints:

    2020-09-24 00:00:00