Skip to content Skip to sidebar Skip to footer

How Can I Generate Posix Values For Yesterday And Today At Midnight In Python?

I've been struggling to determine how I can generate a POSIX (UNIX) time value for today and yesterday (midnight) via Python. I created this code, but keep stumbling with how to co

Solution 1:

You should apply the timetuple() method to the today object, not to the result of time.mktime(today):

>>>time.mktime(today.timetuple())
1345845600.0

By the way, I'm wrong or yesterday will be equal to today in your code?

edit: To obtain the POSIX time for today you can simply do:

time.mktime(datetime.date.today().timetuple())

Solution 2:

@Bakuriu is right here. But you are making this overcomplex.

Take a look at this:

from datetime import date, timedelta
import time

today = date.today()
today_unix = time.mktime(today.timetuple())

yesterday = today - timedelta(1)
yesterday_unix = time.mktime(yesterday.timetuple())

Since the date object doesn't hold time, it resets it to the midnight.

You could also replace the last part with:

yesterday_unix = today_unix - 86400

but note that it wouldn't work correctly across daylight saving time switches (i.e. you'll end up with 1 AM or 23 PM).

Solution 3:

Getting a unix timestamp from a datetime object as a string and as a float:

datetime.now().strftime('%s')
'1345884732'time.mktime(datetime.now().timetuple())
1345884732.0

Post a Comment for "How Can I Generate Posix Values For Yesterday And Today At Midnight In Python?"