简体   繁体   English

Python3获取纪元时间第一天和最后一天

[英]Python3 Get epoch time first and last day of month

Given a month and a year, such as 03 2022 , I need to get the epoch time of the first day of the month and the last day of the month.给定月份和年份,例如03 2022 ,我需要获取该月的第一天和该月的最后一天的纪元时间。 I am not sure how to do that.我不知道该怎么做。 Any help would be appreciated.任何帮助,将不胜感激。 Thank you.谢谢你。

  • You can get the beginning of the month easily by setting the day to 1.您可以通过将日期设置为 1 轻松获得月初。
  • To get the end of the month conveniently, you can calculate the first day of the next month, then go back one day.为了方便得到月末,你可以计算下个月的第一天,然后 go 返回一天。
  • Then set the time zone (tzinfo) to UTC to prevent Python using local time.然后将时区 (tzinfo) 设置为 UTC,以防止 Python 使用本地时间。
  • Finally a call to .timestamp()最后调用.timestamp()
import datetime

def date_to_endofmonth(
    dt: datetime.datetime, offset: datetime.timedelta = datetime.timedelta(days=1)
) -> datetime.datetime:
    """
    Roll a datetime to the end of the month.

    Parameters
    ----------
    dt : datetime.datetime
        datetime object to use.
    offset : datetime.timedelta, optional.
        Offset to the next month. The default is 1 day; datetime.timedelta(days=1).

    Returns
    -------
    datetime.datetime
        End of month datetime.
    """
    # reset day to first day of month, add one month and subtract offset duration
    return (
        datetime.datetime(
            dt.year + ((dt.month + 1) // 12), ((dt.month + 1) % 12) or 12, 1
        )
        - offset
    )


year, month = 2022, 11

# make datetime objects; make sure to set UTC
dt_month_begin = datetime.datetime(year, month, 1, tzinfo=datetime.timezone.utc)
dt_month_end = date_to_endofmonth(dt_month_begin).replace(tzinfo=datetime.timezone.utc)

ts_month_begin = dt_month_begin.timestamp()
ts_month_end = dt_month_end.timestamp()

print(ts_month_begin, ts_month_end)
# 1667260800.0 1701302400.0

Unable to comment due to reputation but @FObersteiner is excellent just I would recommend a small change.由于声誉原因无法发表评论,但@FObersteiner 非常出色,只是我建议进行一些小改动。

For example running the current code it would produce this for Nov 2022例如,运行当前代码它将在 2022 年 11 月生成此代码

print(dt_month_begin.timestamp())
print(dt_month_begin)
print(dt_month_end.timestamp())
print(dt_month_end)

---> --->

1667260800.0
2022-11-01 00:00:00+00:00
1701302400.0
2023-11-30 00:00:00+00:00

Note the year field注意年份字段

I'd suggest the following我建议以下

import datetime

def date_to_endofmonth(
    dt: datetime.datetime, offset: datetime.timedelta = datetime.timedelta(seconds=1)
) -> datetime.datetime:
    """
    Roll a datetime to the end of the month.

    Parameters
    ----------
    dt : datetime.datetime
        datetime object to use.
    offset : datetime.timedelta, optional.
        Offset to the next month. The default is 1 second; datetime.timedelta(seconds=1).

    Returns
    -------
    datetime.datetime
        End of month datetime.
    """
    # reset day to first day of month, add one month and subtract offset duration
    return (
        datetime.datetime(
            dt.year + ((dt.month + 1) // 13), ((dt.month + 1) % 12) or 12, 1
        )
        - offset
    )


year, month = 2022, 11

# make datetime objects; make sure to set UTC
dt_month_begin = datetime.datetime(year, month, 1, tzinfo=datetime.timezone.utc)
dt_month_end = date_to_endofmonth(dt_month_begin).replace(tzinfo=datetime.timezone.utc)

Differences being floor division by 13 instead of 12 to handle the month of November.区别在于处理 11 月份的楼层除以 13 而不是 12。

Changing the offset to seconds delta because I felt the user ( and myself who came looking for the answer) wanted the starting epoch time and the ending epoch time so将偏移量更改为秒增量,因为我觉得用户(以及来寻找答案的我自己)想要起始纪元时间和结束纪元时间,所以

Nov 1st 00:00:00 --> Nov 30th 23:59:59 would be better than Nov 1st 00:00:00 --> Nov 30th 00:00:00 ( Losing a day worth of seconds) 11 月 1 日 00:00:00 --> 11 月 30 日 23:59:59 会比 11 月 1 日 00:00:00 好 --> 11 月 30 日 00:00:00(失去一天的秒数)

Output of the above would be:上面的 Output 将是:

1667260800.0
2022-11-01 00:00:00+00:00
1669852799.0
2022-11-30 23:59:59+00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM