如何以大纪元时间获取昨天的日期? [python]

How to get yesterday's date in Epoch time? [python]

我可以像这样轻松获取昨天的日期:

from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(1)
x= datetime.strftime(yesterday, '%Y-%m-%d')

如何为 Unix 纪元时间做同样的事情? 我试过这个:

>>> x=(datetime.now() - timedelta(1)).strftime('%Y, %m, %d')
>>> print(x)
2021, 12, 26
>>> datetime = datetime.date(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)

我现在可以进行一些疯狂的转换,将 str 转换为 int 等等,但这看起来确实有点矫枉过正。 Recon,有没有更简单的方法来做到这一点?

谢谢!

也许你可以使用 datetime.<b>timestamp()</b>:

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
print(f'{yesterday=:%Y-%m-%d}')
yesterday_timestamp = yesterday.timestamp()
print(f'{yesterday_timestamp=}')

示例输出:

yesterday=2021-12-26
yesterday_timestamp=1640521058.458582