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

I am in PST. I want to get 2 timestamps:

  • the beginning of yesterday
  • end of yesterday

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

How can I do this using Python?

Should I use a datetime object and then convert it to a timestamp?

+4
source share
2 answers

To get yesterday , I think 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' 
+6
source

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

Here it is with time :

 import time def yesterday(): now = time.time() yesterday = time.localtime(now - 86400) # seconds/day start = time.struct_time((yesterday.tm_year, yesterday.tm_mon, yesterday.tm_mday, 0, 0, 0, 0, 0 yesterday.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 the leap second, on a platform that tracks the leap seconds, it will give today, not yesterday. You can check it easily (basically, if today == yesterday, subtract another day), but I don't think it's worth it.

Also, if you run this during DST cross-docking in the time zone, where the crossover occurs between midnight and 01:00 or 23:00 (depending on your hemisphere), it will receive the wrong day. For example, in Brazil , if you run this code during the second 23: 00-00: 00 hours on February 16, 2013, it will return the beginning of the day, which includes the time 24 hours ago ... which is today, not yesterday. The same workaround works here.

+1
source

Source: https://habr.com/ru/post/1489599/


All Articles