开发者

python's datetime and end of the month

开发者 https://www.devze.com 2022-12-10 05:03 出处:网络
How to create datetime object representing the very last moment of the cur开发者_开发百科rent month ?Use a simple trick: Set the date to the first of the next month and then subtract one second/hour/d

How to create datetime object representing the very last moment of the cur开发者_开发百科rent month ?


Use a simple trick: Set the date to the first of the next month and then subtract one second/hour/day/as much as you need.


import datetime

def eom(dt):
    sometime_next_month= dt.replace(day=1) + datetime.timedelta(days=31)
    start_of_next_month= sometime_next_month.replace(day=1,hour=0,minute=0,second=0)
    return start_of_next_month - datetime.timedelta(seconds=1)


>>> eom(datetime.datetime(1972, 2, 1, 23, 50, 50))
datetime.datetime(1972, 2, 29, 23, 59, 59)
>>> eom(datetime.datetime(1980, 12, 31))
datetime.datetime(1980, 12, 31, 23, 59, 59)


selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

where 'timedelta(days=1)' might be a difference with next month and last moment of the previous month.

0

精彩评论

暂无评论...
验证码 换一张
取 消