Search code examples
python-3.xdatedatetimetimestamptimedelta

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


Solution

  • 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.