finding first day of the month in python

后端 未结 11 871
挽巷
挽巷 2021-02-02 05:39

I\'m trying to find the first day of the month in python with one condition: if my current date passed the 25th of the month, then the first date variable will hold the first da

相关标签:
11条回答
  • 2021-02-02 05:54

    This is a pithy solution.

    import datetime 
    
    todayDate = datetime.date.today()
    if todayDate.day > 25:
        todayDate += datetime.timedelta(7)
    print todayDate.replace(day=1)
    

    One thing to note with the original code example is that using timedelta(30) will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.

    0 讨论(0)
  • 2021-02-02 05:54

    This could be an alternative to Gustavo Eduardo Belduma's answer:

    import datetime 
    first_day_of_the_month = datetime.date.today().replace(day=1)
    
    0 讨论(0)
  • 2021-02-02 06:02

    You can use dateutil.rrule:

    In [1]: from dateutil.rrule import *
    
    In [2]: rrule(DAILY, bymonthday=1)[0].date()
    Out[2]: datetime.date(2018, 10, 1)
    
    In [3]: rrule(DAILY, bymonthday=1)[1].date()
    Out[3]: datetime.date(2018, 11, 1)
    
    0 讨论(0)
  • 2021-02-02 06:05

    Can be done on the same line using date.replace:

    from datetime import datetime
    
    datetime.today().replace(day=1)
    
    0 讨论(0)
  • 2021-02-02 06:08

    Use arrow.

    import arrow
    arrow.utcnow().span('month')[0]
    
    0 讨论(0)
提交回复
热议问题