How would I compute exactly 30 days into the past with Python (down to the minute)?

63,574

You want to use a datetime object instead of just a date object:

start_date = datetime.datetime.now() - datetime.timedelta(30)

date just stores a date and time just a time. datetime is a date with a time.

Share:
63,574
Nick Sergeant
Author by

Nick Sergeant

Web developer, designer, what have you.

Updated on July 08, 2022

Comments

  • Nick Sergeant
    Nick Sergeant almost 2 years

    In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing:

    >>> import datetime
    >>> start_date = datetime.date.today() + datetime.timedelta(-30)
    

    Which returns a datetime object, but with no time data:

    >>> start_date.year
    2009
    >>> start_date.hour
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'datetime.date' object has no attribute 'hour'
    
  • radtek
    radtek over 5 years
    Works same way, but I like to look at it this way datetime.datetime.now() - datetime.timedelta(days=30)
  • therealak12
    therealak12 almost 4 years
    Because explicit is better than implicit, I do prefer this.
  • claudius
    claudius over 2 years
    Also works for me: datetime.datetime.today() - datetime.timedelta(days=30)