Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Date difference in minutes in Python
Next article icon

Python - Timedelta object with negative values

Last Updated : 20 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, there is the Datetime library which is the in-built library under which timedelta() function is present. Using this function we can find out the future date and time or past date and time. In timedelta() object delta represents the difference between two dates or times.

Syntax:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minute=0, hours=0, weeks=0)

All the arguments are optional and are 0 by default. We can pass both positive and negative values in the arguments.

Let's see some examples for better understanding of the topic.

Example 1: Finding estimate date by using timedelta object with negative values.

Python3
# importing datetime and timedelta from  # datetime module from datetime import datetime, timedelta  # function to return date def get_date(current_date):        # creating timedelta object with negative     # values     date_obj = timedelta(days=-534)          # getting required date     req_date = current_date + date_obj          # splitting date from resultant datetime     date = req_date.date()          # returning date     return date   # main function if __name__ == '__main__':        # getting current date and time     current_datetime = datetime.now()          # calling function to get the date     resulted_date = get_date(current_datetime)          # printing current date     print('Current date is:', current_datetime.date())          # printing resultant date after using timedelta     print('Resultant time after using timedelta object is:',            resulted_date) 

Output:

Current date is: 2021-03-24 Resultant time after using timedelta object is: 2019-10-07

The above example shows the current date and the date after using timedelta object, in the above example we had passed days=-534 as a parameter in timedelta object. The negative value represents the past whereas the positive value represents the future, in the above code, we had passed -534 days this means that we are getting a date that is 534 days back from today's date.

Example 2: Finding estimate time by using timedelta object with negative values.

Python3
# importing datetime and timedelta from # datetime module from datetime import datetime, timedelta  # function to return time def get_time(current_time):        # creating timedelta object with negative      # values     time_obj = timedelta(hours=-12, minutes=-15)          # getting required time     req_time = current_time + time_obj          # splitting time from resultant datetime     time = req_time.time()          # returning time     return time   # main function if __name__ == '__main__':          # getting current date and time     current_datetime = datetime.now()          # calling function to get the time     resulted_time = get_time(current_datetime)          # printing current time     print('Current time is:', current_datetime.time())          # printing resultant time after using timedelta     print('Resultant time after using timedelta object is:',            resulted_time) 

Output:

Current time is: 15:53:37.019928 Resultant time after using timedelta object is: 03:38:37.019928

The above example shows the current time and the time after using timedelta object, in the above code we had passed hours=-12 and minutes=-15 that means we are getting resultant time i.e, before 12 hours and 15 minutes from now onwards.

Example 3: Another way of finding estimate time by using timedelta object with negative values.

Python3
# importing datetime and timedelta from  # datetime module from datetime import datetime, timedelta  # function to return time def get_time(current_time):          # creating timedelta object with negative      # values     time_obj = timedelta(hours=15, minutes=25)          # getting required time     req_time = current_time - time_obj          # splitting time from resultant datetime     time = req_time.time()          # returning time     return time   # main function if __name__ == '__main__':          # getting current date and time     current_datetime = datetime.now()          # calling function to get the time     resulted_time = get_time(current_datetime)          # printing current time     print(f'Current time is: {current_datetime.time()}')          # printing resultant time after using timedelta     print(f'Resultant time after using timedelta object is: {resulted_time}') 

Output:

Current time is: 15:52:59.538796 Resultant time after using timedelta object is: 00:27:59.538796

In the above example, we had passed the positive values in the timedelta object, but they are behaving like negative values because while finding the required_time at line 9 in the above code we had used the negative sign with timedelta object so the values of the parameters which are passed positive become negative automatically, and we get resultant time i.e, before 15 hours and 25 minutes from now onwards.

Example 4: Finding estimate date and time by using timedelta object with negative values.

Python3
# importing datetime and timedelta from datetime module from datetime import datetime,timedelta  # function to return time  def get_datetime(current_datetime):        # creating timedelta object with negative values     time_obj = timedelta(weeks=-1, days=-4,                          hours=-15, minutes=-25,                          seconds=-54)          # getting required time and time      req_time = current_datetime + time_obj          # returning date and time     return req_time  # main function if __name__ == '__main__':          # getting current date and time     current_datetime = datetime.now()          # calling function to get the date and time     resulted_time = get_datetime(current_datetime)          # printing current date and time     print(f'Current time is: {current_datetime}')          # printing resultant date and time after using timedelta      print(f'Resultant time after using timedelta object is: {resulted_time}') 

Output:

Current time is: 2021-03-24 15:51:33.024268 Resultant time after using timedelta object is: 2021-03-13 00:25:39.024268

The above example shows the current date and time and resultant date and time after using timedelta object, in the above code we are passing weeks=-1 days=-4, hours=-15, minutes=-25, seconds=-54 in the timedelta object means we are getting estimated date and time after using timedelta object is 1 week 4 days 15 hours 25 minutes and 54 seconds before from now onwards.


Next Article
Date difference in minutes in Python
author
srishivansh5404
Improve
Article Tags :
  • Python
  • Python-datetime
Practice Tags :
  • python

Similar Reads

  • Python datetime module
    In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
    14 min read
  • Date class

    • Python DateTime - Date Class
      The object of the Date class represents the naive date containing year, month, and date according to the current Gregorian calendar. This date can be extended indefinitely in both directions. The January 1 of year 1 is called day 1 and January 2 or year 2 is called day 2 and so on. Syntax: class dat
      4 min read

    • ctime() Function Of Datetime.date Class In Python
      The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character le
      2 min read

    • fromisoformat() Function Of Datetime.date Class In Python
      The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified
      2 min read

    • Fromordinal() Function Of Datetime.date Class In Python
      The fromordinal() function is used to return the Gregorian date corresponding to a specified Gregorian ordinal. This is the opposite of the toordinal() function that is used to convert a Gregorian date to a Gregorian ordinal. When a negative ordinal value or an ordinal beyond the value returned by t
      2 min read

    • fromtimestamp() Function Of Datetime.date Class In Python
      fromtimestamp() function in Python is used to return the date corresponding to a specified timestamp. A timestamp typically represents the number of seconds since January 1, 1970, known as the Unix epoch. This function is a class method of the datetime.date class, and it converts a given timestamp i
      2 min read

    • isocalendar() Function Of Datetime.date Class In Python
      The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 ful
      2 min read

    • Isoformat() Function Of Datetime.date Class In Python
      The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date needs to be represented using a 4-digit
      3 min read

    • Isoweekday() Function Of Datetime.date Class In Python
      isoweekday() is a function that returns an integer that tells the given date falls on. The integer it returns represents a day according to the table given below. Syntax: datetime.isoweekday() Return Value: an integer in range of [1,7] Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursda
      3 min read

    • timetuple() Function Of Datetime.date Class In Python
      timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time i
      2 min read

    • Get current date using Python
      Prerequisite: DateTime module In Python, Date and Time are not data types of their own, but a module named DateTime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. The DateTime module provides some function
      3 min read

    • toordinal() Function Of Datetime.date Class In Python
      The toordinal() function is used to return the proleptic Gregorian ordinal of a specified datetime instance. Note: The Proleptic Gregorian ordinal gives the number of days elapsed from the date 01/Jan/0001. And here ordinal is called Proleptic since the Gregorian calendar itself is followed from Oct
      2 min read

    • weekday() Function Of Datetime.date Class In Python
      The weekday() function is a built-in method of the datetime.date class in Python. It returns the day of the week as an integer, where Monday is 0 and Sunday is 6. This method is useful when you want to determine the day of the week for a given date. Example: [GFGTABS] Python from datetime import dat
      2 min read

    Time class

    • Python DateTime - Time Class
      Time class represents the local time of the day which is independent of any particular day. This class can have the tzinfo object which represents the timezone of the given time. If the tzinfo is None then the time object is the naive object otherwise it is the aware object. Syntax: class datetime.t
      4 min read

    • Python time.daylight() Function
      Time.daylight() function which returns a non zero integer value when Daylight Saving Time (DST) is defined, else it returns 0. Daylight Saving Time, in short, is called DST which is a best practice of setting a clock time one hour forward from standard time during months of summer and back again in
      2 min read

    • Python time.tzname() Function
      Time tzname() in Python returns the tuple of two strings in which the first string is the name of the local non-DST timezone and the second string is the name of the local DST timezone. Syntax: time.tzname() Return: It will return the tuple of strings Example 1: Python program to get the DST and non
      1 min read

    Datetime class

    • Python DateTime - DateTime Class
      DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unl
      5 min read

    • Python DateTime astimezone() Method
      The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz. Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will
      2 min read

    • Python - time.ctime() Method
      Python time.ctime() method converts a time in seconds since the epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). Current time is returned by localtime() is used when the time tuple is not present. Syntax: time.ctime([ sec ]) Parameter: sec: number of seconds to be
      2 min read

    • Isocalendar() Method Of Datetime Class In Python
      The isocalendar() function is used to return a tuple of ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO year can start as yearly as 29th January or as late a
      2 min read

    • Isoformat() Method Of Datetime Class In Python
      In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calenda
      4 min read

    • Isoweekday() Method Of Datetime Class In Python
      Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the w
      3 min read

    • Datetime.replace() Function in Python
      The datetime.replace() method in Python allows you to modify specific parts of a datetime or date object without changing the original object. Instead, it returns a new modified object with the updated values. For example, suppose we booked a flight for March 15, 2025, at 10:00 AM, but it got resche
      3 min read

    • Python DateTime - strptime() Function
      strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object. Syntax: datetime.strptime(time_data, format_data) Parameter: time_data is the time present in string formatformat_data is the data present in datetime format which
      7 min read

    • Python | time.time() method
      Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. Note: The epoch is the point where the time
      2 min read

    • Python datetime.timetz() Method with Example
      The timetz() function manipulates the objects of the DateTime class of the DateTime module. This function uses an instance method given to it via reference, and converts them, and returns a time object with the same hour, minute, second, microsecond, and fold and tzinfo attributes. Syntax: timetz()
      3 min read

    • Python - datetime.toordinal() Method with Example
      datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object. If January 1 of year 1 has ordinal number 1 the
      2 min read

    • Get UTC timestamp in Python
      UTC timestamp represents a specific point in time as measured from the "Unix epoch" — January 1, 1970, 00:00:00 UTC. This timestamp is often used in computing because it is not affected by time zones or daylight saving time, providing a consistent reference time across the globe. When working with t
      3 min read

    • Python datetime.utcoffset() Method with Example
      The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime.Here range of the utcoffset is "-timedelta(hours=24) <= offset <= timedelta(hours=24)".If the
      3 min read

    Timedelta class

    • Python DateTime - Timedelta Class
      Timedelta class is used for calculating differences between dates and represents a duration. The difference can both be positive as well as negative. Syntax: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Example: C/C++ Code # Timedelta funct
      4 min read

    • Python - Timedelta object with negative values
      In Python, there is the Datetime library which is the in-built library under which timedelta() function is present. Using this function we can find out the future date and time or past date and time. In timedelta() object delta represents the difference between two dates or times. Syntax: datetime.t
      5 min read

    • Date difference in minutes in Python
      To calculate the date difference in minutes in Python, subtract two datetime objects to get the time difference. Then, convert that difference into minutes or break it down into minutes and seconds based on your needs. For example: for two dates, 2025-05-03 18:45:00 and 2025-05-03 16:30:00, the time
      3 min read

    • Python | datetime.timedelta() function
      Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0
      4 min read

    • Python timedelta total_seconds() Method with Example
      The total_seconds() function is used to return the total number of seconds covered for the specified duration of time instance. This function is used in the timedelta class of module DateTime. Syntax: total_seconds() Parameters: This function does not accept any parameter. Return values: This functi
      2 min read

  • datetime.tzinfo() in Python
    datetime.tzinfo() class is an abstract base class in Python that provides the interface for working with time zone information. The tzinfo class itself does not store any time zone data; instead, it is intended to be subclassed. The subclass can provide the logic to convert datetime objects to and f
    3 min read
  • Handling timezone in Python
    There are some standard libraries we can use for timezones, here we'll use pytz. This library has a timezone class for handling arbitrary fixed offsets from UTC and timezones. Installation pytz is a third-party package that you have to install. To install pytz use the following command - pip install
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences