Search code examples
pythontimestamptimedelta

python timestamp and unix dates


I have the following query, getting some data, I need to select those which have been added yesterday only, excluding today. I am struggling to incorporate it in the script.

In my data I have 'created date' which is unix format

docs_all = db.collection('collection').where('created','>','1675863274685').stream()
for doc in docs_all:
    print(doc.to_dict())

I dont know if it is better to convert unix to date or the other way round and how to add date = current_date - 1


Solution

  • If I understand correctly, you need to get an appropriate strings to put into where close to filter only yesterday.

    I suggest calculating today - 1 as date (without hours and minutes), then creating a datetime corresponding to the start of yesterday (00:00:00).

    End of yesterday is start of today + seconds in a day.

    I am assuming you work with milliseconds, but this can be adjusted. Also everything is calculated in UTC.

    from datetime import datetime, timedelta
    from dateutil import tz
    
    today = datetime.utcnow().date() - timedelta(1)
    start = int(datetime(today.year, today.month, today.day, tzinfo=tz.tzutc()).timestamp()) * 1000 # milliseconds
    end = start + 24 * 60 * 60 * 1000
    
    str(start), str(end)
    

    Output:

    ('1689033600000', '1689120000000')