简体   繁体   中英

How to set date to the last 15 days of the previous month and the first 15 days of the next month?

I am trying to create a function that would set the dates in the column Date into the last 15 days of the previous month and the first 15 days of the following month. Also when the month is December days from 16/12 to 31/12/Y should be turned into 01/01/Y+1

Example 
| Date      | Del_Date   |
| ----------| ---------- |
| 14/12/2018| 01/12/2018 |
| 15/12/2018| 01/12/2018 | # sets date to the current month before the 15th
| 16/12/2018| 01/01/2019 | # moves to the next month after the 15th
...
...
...
| 31/12/2018| 01/01/2019|
| 01/01/2019| 01/01/2019|
| 02/01/2019| 01/01/2019|
...
...
...
| 15/01/2019| 01/01/2019|
| 16/01/2019| 01/02/2019|  # moves to the next month after the 15th

What I have tried but isn't working :


def Del_Date(column):

day = column.dt.day
month = column.dt.month
year = column.dt.year

if month ==12 :

    if (day <= 15 & day >=  1 ) :
        return datetime.date(year, month ,1)
    elif (day <= 31 & day >=  16) :
        return datetime.date(year + 1 ,1 ,1)
    else : 'ERROR'

elif month !=12 :

    if (day <= 15 & day >=  1 ) :
        return datetime.date(year, month ,1)
    elif (day <= 31 & day >=  16) :
        return datetime.date(year, month+1 , 1 )
    else : 'ERROR'
df['Del_Date'] = df.apply(Del_Date, axis=1)

Trick is to make use of datetime.timedelta

You can achieve the same with below:

import datetime

def get_desired_date(date: datetime):
    new_date = datetime.date(date.year, date.month, 1)
    if date.day <= 15:
        return new_date

    # Adding 31 days to day 1 of month to make sure we are in next month
    new_date = new_date + datetime.timedelta(days=31)    
    return datetime.date(new_date.year, new_date.month, 1)

Execute as below for example:

print(get_desired_date(datetime.date(2022, 12, 15)))
print(get_desired_date(datetime.date(2022, 12, 14)))
print(get_desired_date(datetime.date(2022, 12, 1)))
print(get_desired_date(datetime.date(2022, 12, 16)))
print(get_desired_date(datetime.date(2023, 1, 1)))

Examples output:

2022-12-01
2022-12-01
2022-12-01
2023-01-01
2023-01-01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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