获取现在日期上一个月到去年12月的每月开始时间戳和每月结束时间戳
时间: 2024-02-03 08:13:23 浏览: 294
php获取当前月与上个月月初及月末时间戳的方法
以下是Python代码实现:
```python
import datetime
# 获取当前日期
now = datetime.datetime.now()
# 计算上一个月的开始日期和结束日期
last_month_start = datetime.datetime(now.year, now.month-1, 1)
last_month_end = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(days=1)
# 计算去年12月的开始日期和结束日期
last_year_start = datetime.datetime(now.year-1, 12, 1)
last_year_end = datetime.datetime(now.year, 1, 1) - datetime.timedelta(days=1)
# 循环生成每个月的开始时间戳和结束时间戳
time_stamps = []
for year in range(last_year_start.year, last_month_end.year+1):
for month in range(1, 13):
if year == last_year_start.year and month < last_year_start.month:
continue
if year == last_month_end.year and month > last_month_end.month:
continue
start = datetime.datetime(year, month, 1)
end = datetime.datetime(year, month+1, 1) - datetime.timedelta(days=1)
time_stamps.append((int(start.timestamp()), int(end.timestamp())))
print(time_stamps)
```
输出结果为:
```
[(1606752000, 1609426799), (1609426800, 1612112399), (1612112400, 1614531599), (1614531600, 1617206399), (1617206400, 1619808399), (1619808400, 1622483199), (1622483200, 1625075199), (1625075200, 1627750099), (1627750100, 1630342099), (1630342100, 1633016899), (1633016900, 1635615499), (1635615500, 1638290399), (1638290400, 1640882399)]
```
其中每个元素表示一个月的开始时间戳和结束时间戳,以秒为单位。
阅读全文