generate today's midnight in python

To generate today's midnight in Python, we can use the datetime module to get the current date and the time module to get midnight. We need to specify the timezone to be aware of any daylight saving changes.

main.py
from datetime import datetime, time
from pytz import timezone

tz = timezone('US/Eastern') # set timezone to desired timezone
today = datetime.now(tz).date() # get today's date in the desired timezone
midnight = tz.localize(datetime.combine(today, time.min)) # combine today's date with midnight and set timezone

print(midnight) # output midnight in the desired timezone
372 chars
9 lines

The code above will output something like 2021-10-29 00:00:00-04:00, which is today's midnight in the Eastern timezone. The naive approach, without using pytz library would be prone to errors during the daylight saving changes.

gistlibby LogSnag