获取指定年月当月首日零点与末日23:59:59的Epoch时间戳
嘿,这需求太常见了!我来给你捋清楚怎么快速拿到指定年月的月初零点和月末23:59:59的Epoch时间戳,下面分几种主流编程语言给你具体实现:
Python 实现方案
首先咱得用Python的datetime和time模块来处理日期时间,核心思路是:
- 直接构造当月第一天的午夜零点时间
- 先拿到下个月的第一天,再减去1秒,就能精准得到当月最后一天的23:59:59(完美避开不同月份天数不同的麻烦)
代码示例:
import datetime import time def get_month_epoch(year, month): # 构造当月第一天的datetime对象(固定00:00:00) first_day = datetime.datetime(year, month, 1, 0, 0, 0) # 计算下个月第一天:12月的话年份+1、月份转1,否则直接月份+1 if month == 12: next_month_first = datetime.datetime(year + 1, 1, 1, 0, 0, 0) else: next_month_first = datetime.datetime(year, month + 1, 1, 0, 0, 0) # 下个月第一天减1秒,就是当月最后一刻 last_day = next_month_first - datetime.timedelta(seconds=1) # 转成秒级Epoch时间戳 first_epoch = int(time.mktime(first_day.timetuple())) last_epoch = int(time.mktime(last_day.timetuple())) return first_epoch, last_epoch # 测试:比如2018年3月 first, last = get_month_epoch(2018, 3) print(f"月初零点Epoch: {first}") print(f"月末23:59:59Epoch: {last}")
注意:上面的代码用的是本地时区的时间戳,如果需要UTC时间戳,可以把time.mktime换成first_day.timestamp()(Python 3.3+支持),记得提前处理时区设置哦!
JavaScript 实现方案
JS里用Date对象处理的思路和Python一致,但要注意JS的月份是0-11索引的,别踩坑!
代码示例:
function getMonthEpoch(year, month) { // 重要:JS月份从0开始,所以传入的月份要减1 const firstDay = new Date(year, month - 1, 1, 0, 0, 0); // 下个月第一天:12月的话年份+1、月份转0,否则直接月份+1 const nextMonthFirst = new Date(year, month, 1, 0, 0, 0); // 减1000毫秒(1秒)得到月末最后一刻 const lastDay = new Date(nextMonthFirst.getTime() - 1000); // 转成毫秒级Epoch时间戳(要秒级就除以1000取整) const firstEpoch = firstDay.getTime(); const lastEpoch = lastDay.getTime(); return [firstEpoch, lastEpoch]; } // 测试:2018年9月 const [first, last] = getMonthEpoch(2018, 9); console.log(`月初零点Epoch(毫秒): ${first}`); console.log(`月末23:59:59Epoch(毫秒): ${last}`);
划重点:如果需要UTC时间,就用Date.UTC()来创建日期对象,比如new Date(Date.UTC(year, month-1, 1, 0, 0, 0))。
通用思路总结
不管用什么语言,核心逻辑都是这两步:
- 精准定位当月第一天的00:00:00,直接转成时间戳
- 通过下个月第一天的00:00:00减去1秒,得到当月最后一天的23:59:59,完全不用纠结每个月有多少天,省心又准确!
内容的提问来源于stack exchange,提问作者Ohad Benita
相关产品推荐
相关产品推荐

