Search code examples
pythonunix-timestamppython-datetime

Calculate unix timestamps for midnight


I have an interval of Unix timestamps (since 1970) starting from 1593262800000 (2020-06-27) to 1594142579000 (2020-07-07). Now, I would like to calculate all timestamps for midnight in this interval. That means midnight at 2020-06-27, midnight at 2020-06-28 and so on.

How can I do this?


Solution

  • Like this?

    import datetime
    
    ms_per_day = 24 * 3600 * 1000
    
    a = 1593262800000
    b = 1594142579000
    
    ms_until_midnight = ms_per_day - a % ms_per_day 
    
    for e in range(a + ms_until_midnight, b, ms_per_day):
        print(e, datetime.datetime.utcfromtimestamp(e/1000))
    

    output:

    1593302400000 2020-06-28 00:00:00
    1593388800000 2020-06-29 00:00:00
    1593475200000 2020-06-30 00:00:00
    1593561600000 2020-07-01 00:00:00
    1593648000000 2020-07-02 00:00:00
    1593734400000 2020-07-03 00:00:00
    1593820800000 2020-07-04 00:00:00
    1593907200000 2020-07-05 00:00:00
    1593993600000 2020-07-06 00:00:00
    1594080000000 2020-07-07 00:00:00