{"id":6579,"date":"2020-06-28T08:37:44","date_gmt":"2020-06-28T08:37:44","guid":{"rendered":"https:\/\/www.askpython.com\/?p=6579"},"modified":"2023-02-16T19:57:03","modified_gmt":"2023-02-16T19:57:03","slug":"python-timedelta","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-timedelta","title":{"rendered":"How to Work with Python TimeDelta?"},"content":{"rendered":"\n<p>Hello everyone! In today&#8217;s article, we&#8217;ll be taking a look at using the Python timedelta object.<\/p>\n\n\n\n<p>This object is really useful if you want to represent an instance of time, as an object.<\/p>\n\n\n\n<p>As opposed to an integer \/ float number, this is an actual object. The advantage is that it gives us more flexibility for integrating with our application!<\/p>\n\n\n\n<p>Let&#8217;s look at how we can use this, using some simple examples!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python timedelta object<\/h2>\n\n\n\n<p>This class is available in the <code>datetime<\/code> module, which is a part of the standard library.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import timedelta\n<\/pre><\/div>\n\n\n<p>We can create a timedelta object using the constructor for it&#8217;s class.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import timedelta\n\ntimedelta_object = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)\nprint(timedelta_object)\n\n# Same as above (Everything set to 0)\nzero_obj = timedelta()\nprint(zero_obj)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n0:00:00\n0:00:00\n<\/pre><\/div>\n\n\n<p>Notice that we can customize the parameters to make our own datetime object. If you don&#8217;t set the argument value, it is taken as 0 by default.<\/p>\n\n\n\n<p>Arguments may be integers or floats and may be positive or negative.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Manipulating existing Python timedelta objects<\/h2>\n\n\n\n<p>Other than creating our own timedelta objects, we can also manipulate existing timedelta objects.<\/p>\n\n\n\n<p>We can add, subtract, or divide two timedelta objects using <a href=\"https:\/\/www.askpython.com\/python\/python-operators\" class=\"rank-math-link\">basic operators<\/a>!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\na = timedelta(hours=4, seconds=100)\nprint(a)\nb = timedelta(hours=2, seconds=50)\nprint(b)\nprint(&quot;Output:&quot;)\nprint(a + b, a - b, a \/ b, sep=&#039;\\n&#039;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n4:01:40\n2:00:50\nOutput:\n6:02:30\n2:00:50\n2.0\n<\/pre><\/div>\n\n\n<p>As you can see, we can directly manipulate these objects using simple operations!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Getting the current datetime object<\/h2>\n\n\n\n<p>Now, for most real life programs, we would want to use the current time and store it as a datetime object.<\/p>\n\n\n\n<p>We can use <a href=\"https:\/\/www.askpython.com\/python\/examples\/current-date-and-time-in-python\" class=\"rank-math-link\">datetime.now()<\/a> function to display the current time as a datetime object!<\/p>\n\n\n\n<p>Note that you have to import this from the module name separately!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n<\/pre><\/div>\n\n\n<p>Let&#8217;s now take an example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n\ncurrent_datetime = datetime.now()\nprint(current_datetime)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndatetime.datetime(2020, 6, 27, 22, 45, 54, 267673)\n<\/pre><\/div>\n\n\n<p>The output seems to match! It says that the current time is June 27 2020, 22:45:54 in my local timezone (IST).<\/p>\n\n\n\n<p>Now, we can also use basic operators to get the past or future time!<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, timedelta\n\ncurrent_datetime = datetime.now()\n\n# future dates\none_year_future_date = current_datetime + timedelta(days=365)\n\nprint(&#039;Current Date:&#039;, current_datetime)\nprint(&#039;One year from now Date:&#039;, one_year_future_date)\n\n# past dates\nthree_days_before_date = current_datetime - timedelta(days=3)\nprint(&#039;Three days before Date:&#039;, three_days_before_date)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nCurrent Date: 2020-06-27 22:45:54.267673\nOne year from now Date: 2021-06-27 22:45:54.267673\nThree days before Date: 2020-06-24 22:45:54.267673\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Using Python timedelta with date and time<\/h2>\n\n\n\n<p>We can also use the Python timedelta class with a date object, using addition and subtraction.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, timedelta\n\ncurrent_datetime = datetime.now()\n\ndt = current_datetime.date()\nprint(&#039;Current Date:&#039;, dt)\ndt_tomorrow = dt + timedelta(days=1)\nprint(&#039;Tomorrow Date:&#039;, dt_tomorrow)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nCurrent Date: 2020-06-27\nTomorrow Date: 2020-06-28\n<\/pre><\/div>\n\n\n<p>This gives us more flexibility when trying to store\/display timestamps. If you want a minimally formatted timestamp, using <code>datetime_object.date()<\/code> is a good choice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python timedelta total seconds<\/h2>\n\n\n\n<p>We can display the total number of seconds for any timedelta object using:<br><code>timedelta_object.total_seconds()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import timedelta\n\nprint(&#039;Seconds in an year:&#039;, timedelta(days=365).total_seconds())\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nOutput: Seconds in an year: 31536000.0\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using datetime objects for a specific timezone<\/h2>\n\n\n\n<p>You may want to use a different timezone when you&#8217;re storing\/displaying datetime objects. Python gives us a handy way to do this, using the <code>pytz<\/code> module (Python Timezones).<\/p>\n\n\n\n<p>You can install <code>pytz<\/code> using <code>pip<\/code>, if you haven&#8217;t done so already.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npip install pytz\n<\/pre><\/div>\n\n\n<p>Now, we can use <code>pytz.timezone(TIMEZONE)<\/code> to choose our timezone, and pass it to our timedelta object.<\/p>\n\n\n\n<p>Here&#8217;s a simple example which prints the same time with different timezones.<\/p>\n\n\n\n<p><strong>Handy Tip<\/strong>: You can list the common timezones using <code>pytz.common_timezones<\/code><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\nfrom pytz import timezone, common_timezones\n\ndatetime_object = datetime.now(timezone(&#039;Asia\/Kolkata&#039;))\nprint(&quot;Current IST:&quot;, datetime_object)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nCurrent IST: 2020-06-27 23:27:49.003020+05:30\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\nfrom pytz import timezone, common_timezones\nimport random\n\nfor _ in range(4):\n    zone = random.choice(common_timezones)\n    print(f&quot;Using TimeZone: {zone}&quot;)\n    datetime_object = datetime.now(timezone(zone))\n    print(datetime_object)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nUsing TimeZone: America\/St_Lucia\n2020-06-27 13:57:04.804959-04:00\nUsing TimeZone: Asia\/Muscat\n2020-06-27 21:57:04.814959+04:00\nUsing TimeZone: Asia\/Urumqi\n2020-06-27 23:57:04.825990+06:00\nUsing TimeZone: Asia\/Seoul\n2020-06-28 02:57:04.836994+09:00\n<\/pre><\/div>\n\n\n<p>Indeed, we were able to get the current time in different timezones!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned how we could use the timedelta object to represent time as a Python object!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Python timedelta<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Hello everyone! In today&#8217;s article, we&#8217;ll be taking a look at using the Python timedelta object. This object is really useful if you want to represent an instance of time, as an object. As opposed to an integer \/ float number, this is an actual object. The advantage is that it gives us more flexibility [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":6581,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-6579","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6579","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=6579"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6579\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/6581"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=6579"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=6579"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=6579"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}