TIMEX
TIMEX

Reputation: 271584

In Python, how can I get the Unix timestamp of the day before?

I'm in PST time. I want to get 2 timestamps:

  1. the beginning of yesterday
  2. the end of yesterday

These timestamps should be the same no matter what time it is currently.

How can I do this with Python?

Do I have to use the datetime object, and then transform it to timestamp?

Upvotes: 15

Views: 26480

Answers (2)

abarnert
abarnert

Reputation: 365577

The obvious way to do this is with datetime. But you apparently want to avoid that for some strange reason. Well, you can use time or calendar, or various third-party libraries, or custom code instead.

Here it is with time:

import time

def yesterday():
    now = time.time()
    yday = time.localtime(now - 86400) # seconds/day
    start = time.struct_time((yday.tm_year, yday.tm_mon, yday.tm_mday, 0, 0, 0, 0, 0, yday.tm_isdst))
    today = time.localtime(now)
    end = time.struct_time((today.tm_year, today.tm_mon, today.tm_mday, 0, 0, 0, 0, 0, today.tm_isdst))
    return time.mktime(start), time.mktime(end)

If you run this during a leap second, on a platform that tracks leap seconds, it will give today instead of yesterday. You can check for that easily (basically, if today == yesterday, subtract another day), but I don't think it's worth it.

Also, if you run this during DST crossover in a timezone where the crossover happens between midnight and 01:00 or 23:00 (depending on your hemisphere), it will get the wrong day. For example, in Brazil, if you ran this code during the second 23:00-00:00 hour on 16 February 2013, it would return the start of the day that includes the time 24 hours ago… which is today, rather than yesterday. The same workaround works here.

Upvotes: 1

user1786283
user1786283

Reputation:

To get yesterday I guess you can do this:

>>>import datetime
>>>yesterday = datetime.date.today() - datetime.timedelta(1)
>>>unix_time= yesterday.strftime("%s") #Second as a decimal number [00,61] (or Unix Timestamp)
>>>print unix_time
'1372737600'

Upvotes: 27

Related Questions