Python: get datetime for '3 years ago today'

python string to datetime
python datetime now
python time
strptime python
python datetime timezone
python timedelta example
python timestamp
python datetime now format

In Python, how do I get a datetime object for '3 years ago today'?

UPDATE: FWIW, I don't care hugely about accuracy... i.e. it's Feb 29th today, I don't care whether I'm given Feb 28th or March 1st in my answer. Concision is more important than configurability, in this case.

import datetime
datetime.datetime.now() - datetime.timedelta(days=3*365)

Python Datetime, Import the datetime module and display the current date: import datetime. x = datetime.datetime.now() Return the year and name of weekday: import datetime. x = datetime.datetime.now() Create a date object: import datetime. x = datetime.datetime(2020, 5, 17) Display the name of the month: import datetime. In this article, you will learn to get today's date and current date and time in Python. We will also format the date and time in different formats using strftime() method.

If you need to be exact use the dateutil module to calculate relative dates

from datetime import datetime
from dateutil.relativedelta import relativedelta

three_yrs_ago = datetime.now() - relativedelta(years=3)

How to get the current time in Python, Use: >>> import datetime >>> datetime.datetime.now() datetime.datetime(2009, 1 , 6, 15, 8, 24, 78915) >>> print(datetime.datetime.now()) 2009-01-06 15:08:� python getDateTime1.py 2017-03-06 16:00:04.159338 Get Current Date Time Attributes in Python. You can also get the specific attribute of date and time. For example, if you want to get only current year or month or date etc. create a getDateTime2.py file with following content, which will help you to understand to fetch specific attribute.

Subtracting 365*3 days is wrong, of course--you're crossing a leap year more than half the time.

dt = datetime.now()
dt = dt.replace(year=dt.year-3)
# datetime.datetime(2008, 3, 1, 13, 2, 36, 274276)

ED: To get the leap-year issue right,

def subtract_years(dt, years):
    try:
        dt = dt.replace(year=dt.year-years)
    except ValueError:
        dt = dt.replace(year=dt.year-years, day=dt.day-1)
    return dt

datetime — Basic date and time types — Python 3.8.5 documentation, An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year , month , and day . class datetime. In Python, date, time and datetime classes provides a number of function to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. Whenever you manipulate dates or time, you need to import datetime function.

def add_years(dt, years):
    try:
        result = datetime.datetime(dt.year + years, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
    except ValueError:
        result = datetime.datetime(dt.year + years, dt.month, dt.day - 1, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
    return result

>>> add_years(datetime.datetime.now(), -3)
datetime.datetime(2008, 3, 1, 12, 2, 35, 22000)
>>> add_years(datetime.datetime(2008, 2, 29), -3)
datetime.datetime(2005, 2, 28, 0, 0)

Get Current Date and Time using Python, Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime.now() function of� Python : How to convert datetime object to string using datetime.strftime() Python : How to convert a timestamp string to a datetime object using datetime.strptime() Python : Get Last Modification date & time of a file. | os.stat() | os.path.getmtime() How to convert Dataframe column type from string to date time

Although the answer using dateutil is good, an alternative is using the pendulum package on PyPI. For more info, refer to its docs.

>>> import pendulum
>>> dt = pendulum.now().subtract(years=3)
>>> dt
DateTime(2015, 10, 5, 17, 44, 41, 82598, tzinfo=Timezone('America/New_York'))
>>> type(dt)
pendulum.datetime.DateTime

If you'll be needing the current datetime for further use, you should probably first save pendulum.now() to a variable, and then use the variable!

If you really want to avoid the timezone, use .naive().

You shouldn't need to convert the result to a native Python object, but if you really need to, one way to do it is:

>>> import datetime
>>> pydt = datetime.datetime.fromisoformat(dt.isoformat())
>>> pydt
datetime.datetime(2015, 10, 5, 17, 44, 41, 82598, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> type(pydt)
datetime.datetime

Python: Display the current date and time, Python datetime: The datetime module supplies classes for manipulating dates and times in both simple and complex ways. datetime.now(tz=� Python DateTime Format - Formatting is the process of generating a string with how the elements like day, month, year, hour, minutes and seconds be displayed in a string. We will use format codes and strftime() function to format a date and time string from datetime.datetime object.

How to Get Current Date & Time in Python - TecAdmin, You can use now() function of datetime python module. This tutorial will show you various ways to get the current date and time in the python� An example of Python now() to get current local date and time. The following example displays the current local date and time by using the now() function of the datetime. For that, you first need to import datetime module, as shown in the example below:

Using Python datetime to Work With Dates and Times – Real Python, Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists,� The datetime module has a basic timezone class (for handling arbitrary fixed offsets from UTC) and its timezone.utc attribute (a UTC timezone instance). dateutil.tz library brings the IANA timezone database (also known as the Olson database) to Python, and its usage is recommended. IANA timezone database

How to Get the Current Date and Time in Python, We will also learn how to adjust our date and time for different timezones. Finally, we'll look at converting datetime objects to the popular Unix or�

Comments
  • possible duplicate of How to create a DateTime equal to 15 minutes ago?
  • Presumably if it's March 1 today, you want to get March 1 no matter if a leap year occurs in between or not? I think all the existing answers fail in that regard.
  • Almost, but not quite: the difference between 15 minutes, which is invariable, and 3 years, which is not, is significant.
  • @Jason I agree with you, although from the OP's edit he doesn't seem super concerned about that, so that being the case it would be a duplicate.
  • This site really needs a way for the community to override when people accept a clearly incorrect answer. 3*365 days is not 3 years, and there's a correct answer right there.
  • AP257 said: "I don't care hugely about accuracy". I interpreted as "I don't care about leap years"
  • @Diniz: You interpreted it as "I want to be wrong". It's so easy to do this right, it's just plain silly to do it wrong--and it's bizarre to accept this answer when a correct one is available.
  • Is it correct to give a less concise but more accurate answer when the asker explicitly told the opposite?
  • +1 For simplicity. Maybe the OP just wanted an example of how to do something like this in general.
  • Thanks for simplicity. I also don't care about accuracy. I was actually looking for a difference of days anyway.
  • Well, now you have that other issue: datetime.datetime(2008,2,29).replace(year=2005) -> ValueError. It is still more accurate to catch that error and just subtract one extra day I guess.
  • I keep forgetting about replace. It makes for a simpler solution than mine.
  • @Mark: I did at first, too; I initially did what you did. The site seems to have misplaced that version in the edit history, though.
  • What happens after 2100?