-1

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.

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

0

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • this has two lines which aren't needed *and* uses [utcnow](https://blog.ganssle.io/articles/2019/11/utcnow.html) ;-) – FObersteiner Sep 24 '20 at 15:53