Search code examples
python-3.xunix-timestamp

Simple way to get the epoch of 12 AM for today in UTC in Python (3.x)?


I am trying to come up with the epoch of the start of the day (12AM midnight UTC) in Python. I found this snippet:

today = datetime.date.today()
time.mktime((today.year, today.month, today.day, 0, 0, 0, 0, 0, 0))

but the resulting epoch leads to today's date at 5AM. The reason I need this is because I have a script executing a SQL command that needs to filter using epoch time (for some reason, casting or extracting an epoch through native SQL results in my query finishing in 5 minutes, as compared to 12 seconds). I'm guessing that the code snippet I put above uses my local machine time.


Solution

  • You need to figure how what date it is currently in UTC, and then replace the time bits:

    now = datetime.now(timezone.utc)
    midnight = now.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    

    In order to get the epoch, use midnight.timestamp(). This will ensure that the timezone information is applied when calculating the timestamp.