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

发布于 2025-01-15 21:17:23 字数 84 浏览 0 评论 0原文

给定一个月和一年,例如03 2022,我需要获取该月第一天和该月最后一天的纪元时间。我不知道该怎么做。任何帮助将不胜感激。谢谢。

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. I am not sure how to do that. Any help would be appreciated. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半枫 2025-01-22 21:17:23

注意: 请参阅下面的 @segaps 答案;我原来的答案在 (dt.month + 1) // 13 中将楼层除以 12 而不是 13,这给出了 11 月份的错误结果。

  • 你可以开始通过将日期设置为 1 来轻松
  • 获取月末,您可以计算下个月的第一天,然后返回一天(或您需要的任何持续时间),
  • 然后设置将时区 (tzinfo) 转换为 UTC 至阻止Python使用本地时间
  • 最后调用 .timestamp()< /a> 获取 Unix 时间1
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) // 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)

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

print(ts_month_begin, ts_month_end)
# 1667260800.0 1669766400.0
print(datetime.datetime.fromtimestamp(ts_month_begin, tz=datetime.timezone.utc), 
      datetime.datetime.fromtimestamp(ts_month_end, tz=datetime.timezone.utc))
# 2022-11-01 00:00:00+00:00 2022-11-30 00:00:00+00:00

1 请注意,Unix 时间始终表示带有时间的日期,而不仅仅是日期。

Note: see @segaps answer below; my original answer had a floor division by 12 instead of 13 in (dt.month + 1) // 13, which gives incorrect result for the month of November.

  • you can get the beginning of the month easily by setting the day to 1
  • to get the end of the month, you can calculate the first day of the next month, then go back one day (or whatever duration you need)
  • then set the time zone (tzinfo) to UTC to prevent Python using local time
  • finally a call to .timestamp() to get Unix time1
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) // 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)

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

print(ts_month_begin, ts_month_end)
# 1667260800.0 1669766400.0
print(datetime.datetime.fromtimestamp(ts_month_begin, tz=datetime.timezone.utc), 
      datetime.datetime.fromtimestamp(ts_month_end, tz=datetime.timezone.utc))
# 2022-11-01 00:00:00+00:00 2022-11-30 00:00:00+00:00

1 Note that Unix time always represents a date with a time, not only a date.

骑趴 2025-01-22 21:17:23

由于声誉无法发表评论,但 @FObersteiner 非常好,只是我建议进行一些小改动。

例如,运行当前代码将在 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

注意年份字段

我建议以下

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)

差异是按 13 而不是 12 进行底面划分来处理 11 月份。

将偏移量更改为秒增量,因为我觉得用户(以及来寻找答案的我自己)想要开始纪元时间和结束纪元时间,所以

11 月 1 日 00:00:00 --> 11 月 30 日 23:59:59 会比
11 月 1 日 00:00:00 --> 11 月 30 日 00:00:00 (损失一天的秒数)

上述输出将是
:

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

Unable to comment due to reputation but @FObersteiner is excellent just I would recommend a small change.

For example running the current code it would produce this for Nov 2022

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.

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)

Output of the above would be
:

1667260800.0
2022-11-01 00:00:00+00:00
1669852799.0
2022-11-30 23:59:59+00:00
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文