{"id":6153,"date":"2022-06-03T17:16:42","date_gmt":"2022-06-03T15:16:42","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=6153"},"modified":"2026-01-15T10:09:30","modified_gmt":"2026-01-15T09:09:30","slug":"the-datetime-and-time-modules-in-python","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/06\/03\/the-datetime-and-time-modules-in-python\/","title":{"rendered":"The datetime and time modules in Python"},"content":{"rendered":"<p>The\u00a0 <i>datetime <\/i>module provides <b>classes for working with date and time<\/b>.\u00a0Date and time have countless uses and it&#8217;s probably hard to find a production application that doesn&#8217;t use them.<\/p>\n<p><!--more--><\/p>\n<p>1. To create a <code><strong>date()<\/strong><\/code> object, you must pass the year, month, and day arguments as follows:<\/p>\n<pre class=\"lang:default decode:true \">from datetime import date\r\n\r\nmy_date = date(2020, 9, 29)\r\nprint(\"Year:\", my_date.year) # Year: 2020\r\nprint(\"Month:\", my_date.month) # Month: 9\r\nprint(\"Day:\", my_date.day) # Day: 29\r\n<\/pre>\n<p>The <code>date<\/code> object has three (read-only) attributes: year, month, and day.<\/p>\n<p>&nbsp;<\/p>\n<p>2. The <code><strong>today()<\/strong><\/code> method returns a date object representing the current local date:<\/p>\n<pre class=\"lang:default decode:true \">from datetime import date\r\nprint(\"Today:\", date.today()) # Displays: Today: 2020-09-29<\/pre>\n<p>or<\/p>\n<pre class=\"lang:default decode:true\">from datetime import date\r\n\r\ntoday = date.today()\r\n\r\nprint(\"Today:\", today)\r\nprint(\"Year:\", today.year)\r\nprint(\"Month:\", today.month)\r\nprint(\"Day:\", today.day)<\/pre>\n<p>&nbsp;<\/p>\n<p>3. In Unix, the timestamp expresses the number of seconds since January 1, 1970, 00:00:00 (UTC). This date is called the<em> &#8220;Unix epoch&#8221;<\/em>, because it began the counting of time on Unix systems. The timestamp is actually the difference between a particular date (including time) and January 1, 1970, 00:00:00 (UTC), expressed in seconds. To create a date object from a timestamp, we must pass a Unix timestamp to the <strong><code>fromtimestamp<\/code> <\/strong>method:<\/p>\n<pre class=\"lang:default decode:true\">from datetime import date\r\nfrom datetime import time\r\n\r\ntimestamp = time.time()\r\nprint(\"Timestamp:\", timestamp)\r\n\r\nd = date.fromtimestamp(timestamp)\r\nprint(\"Date:\", d)<\/pre>\n<p><code>Timestamp: 1767643499.6537435<\/code><br \/>\n<code>Date: 2026-01-05<\/code><\/p>\n<p>Note: The <code><strong>time()<\/strong><\/code> function returns the number of seconds from January 1, 1970 to the current moment in the form of a float number.<\/p>\n<p>&nbsp;<\/p>\n<p>4. The constructor of the <strong><code>time<\/code> <\/strong>class accepts six arguments (<i>hour<\/i>, <i>minute<\/i>, <i>second<\/i>, <i>microsecond<\/i>, <i>tzinfo<\/i>, and <i>fold<\/i>). Each of these arguments is optional.<\/p>\n<pre class=\"lang:default decode:true\">from datetime import time\r\n\r\nt = time(14, 53, 20, 1)\r\n\r\nprint(\"Time:\", t)\r\nprint(\"Hour:\", t.hour)\r\nprint(\"Minute:\", t.minute)\r\nprint(\"Second:\", t.second)\r\nprint(\"Microsecond:\", t.microsecond)<\/pre>\n<p><code>Time: 14:53:20.000001<\/code><br \/>\n<code>Hour: 14<\/code><br \/>\n<code>Minute: 53<\/code><br \/>\n<code>Second: 20<\/code><br \/>\n<code>Microsecond: 1<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>5. The <strong><code>time<\/code> <\/strong>module contains the <strong><code>sleep()<\/code> <\/strong>function, which suspends program execution for a given number of seconds, e.g.:<\/p>\n<pre class=\"lang:default decode:true\">import time\r\n\r\ntime.sleep(10)\r\nprint(\"Hello world!\") # This text will be displayed after 10 seconds.<\/pre>\n<p>&nbsp;<\/p>\n<p>6. In the <strong><code>datetime<\/code> <\/strong>module, date and time can be represented either as separate objects, or as one object. The class that combines date and time is called <i>datetime<\/i>. All arguments passed to the constructor go to read-only class attributes. They are <i>year<\/i>, <i>month<\/i>, <i>day<\/i>, <i>hour<\/i>, <i>minute<\/i>, <i>second<\/i>, <i>microsecond<\/i>, <i>tzinfo<\/i>, and <i>fold<\/i>:<\/p>\n<pre class=\"lang:default decode:true\">from datetime import datetime\r\n\r\ndt = datetime(2020, 9, 29, 13, 51)\r\nprint(\"Datetime:\", dt) # Displays: Datetime: 2020-09-29 13:51:00<\/pre>\n<p>&nbsp;<\/p>\n<p>7. The <strong><code>strftime()<\/code> <\/strong>method takes only one argument in the form of a string specifying a format that can consist of directives. A directive is a string consisting of the character <code>%<\/code> (percent) and a lower-case or upper-case letter. Below are some useful directives:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code>%Y<\/code> \u2013 returns the year with the century as a decimal number;<\/li>\n<li><code>%m<\/code> \u2013 returns the month as a zero-padded decimal number;<\/li>\n<li><code>%d<\/code> \u2013 returns the day as a zero-padded decimal number;<\/li>\n<li><code>%H<\/code> \u2013 returns the hour as a zero-padded decimal number;<\/li>\n<li><code>%M<\/code> \u2013 returns the minute as a zero-padded decimal number;<\/li>\n<li><code>%S<\/code> \u2013 returns the second as a zero-padded decimal number.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Example:<\/p>\n<pre class=\"lang:default decode:true\">from datetime import date\r\n\r\nd = date(2020, 9, 29)\r\nprint(d.strftime('%Y\/%m\/%d')) # Displays: 2020\/09\/29<\/pre>\n<p>or<\/p>\n<pre class=\"lang:default decode:true \">from datetime import time, datetime\r\n\r\nt = time(14, 53)\r\nprint(t.strftime(\"%H:%M:%S\"))\r\n\r\ndt = datetime(2020, 11, 4, 14, 53)\r\nprint(dt.strftime(\"%y\/%B\/%d %H:%M:%S\"))\r\n<\/pre>\n<p><code>14:53:00<\/code><br \/>\n<code>20\/November\/04 14:53:00<\/code><\/p>\n<p>The <code>%B<\/code> directive returns the month as the locale\u2019s full name (in our example, it&#8217;s November).<\/p>\n<p>The <code>strftime<\/code> function is also available in the <code>time<\/code> module. It differs slightly from the <code>strftime<\/code> methods in the classes provided by the <code>datetime<\/code> module because, in addition to the format argument, it can also take (optionally) a tuple or struct_time object.<\/p>\n<pre class=\"lang:default decode:true \">import time\r\n\r\ntimestamp = 1572879180\r\nst = time.gmtime(timestamp)\r\n\r\nprint(time.strftime(\"%Y\/%m\/%d %H:%M:%S\", st))\r\nprint(time.strftime(\"%Y\/%m\/%d %H:%M:%S\"))<\/pre>\n<p><code>2019\/11\/04 14:53:00<\/code><br \/>\n<code>2026\/01\/10 21:19:50<\/code><\/p>\n<p>You can find all available directives in the <code>time<\/code> module <a href=\"https:\/\/docs.python.org\/3\/library\/time.html#time.strftime\" target=\"_blank&quot;\" rel=\"noopener\">here<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<p>8. Knowing how to create a format can be helpful when using a method called <strong><code>strptime<\/code> <\/strong>in the <code>datetime<\/code> class. Unlike the <code>strftime<\/code> method, it creates a <code>datetime<\/code> object from a string representing a date and time.<\/p>\n<pre class=\"lang:default decode:true \">from datetime import datetime\r\nprint(datetime.strptime(\"2019\/11\/04 14:53:00\", \"%Y\/%m\/%d %H:%M:%S\"))<\/pre>\n<p><code>2019-11-04 14:53:00<\/code><\/p>\n<p>Be careful, because if the format you specify doesn&#8217;t match the date and time in the string, it&#8217;ll raise a <i>ValueError<\/i>.<\/p>\n<p>&nbsp;<\/p>\n<p>9. It&#8217;s possible to perform calculations on <strong><code>date<\/code> <\/strong>and <strong><code>datetime<\/code> <\/strong>objects, e.g.:<\/p>\n<pre class=\"lang:default decode:true \">from datetime import date\r\n\r\nd1 = date(2020, 11, 4)\r\nd2 = date(2019, 11, 4)\r\n\r\nd = d1 - d2\r\nprint(d)\r\nprint(d * 2)<\/pre>\n<p><code>366 days, 0:00:00<\/code><br \/>\n<code>732 days, 0:00:00<\/code><\/p>\n<p>The result of the subtraction is returned as a <strong><code>timedelta<\/code> <\/strong>object that expresses the difference in days between the two dates in the example above.<\/p>\n<p>Note that the difference in hours, minutes, and seconds is also displayed. The <code>timedelta<\/code> object can be used for further calculations (e.g. you can multiply it by 2).<\/p>\n<p>You can also create an timedelta object yourself. For this purpose, let&#8217;s get acquainted with the arguments accepted by the class constructor, which are: <code>days<\/code>, <code>seconds<\/code>, <code>microseconds<\/code>, <code>milliseconds<\/code>, <code>minutes<\/code>, <code>hours<\/code>, and <code>weeks<\/code>. Each of them is optional and defaults to 0.<\/p>\n<pre class=\"lang:default decode:true \">from datetime import timedelta\r\n\r\ndelta = timedelta(weeks=2, days=2, hours=3)\r\nprint(delta)<\/pre>\n<p><code>16 days, 3:00:00<\/code><\/p>\n<p>or<\/p>\n<pre class=\"lang:default decode:true\">from datetime import timedelta\r\n\r\ndelta = timedelta(weeks=2, days=2, hours=3)\r\nprint(\"Days:\", delta.days)\r\nprint(\"Seconds:\", delta.seconds)\r\nprint(\"Microseconds:\", delta.microseconds)\r\n\r\n<\/pre>\n<p><code>Days: 16<\/code><br \/>\n<code>Seconds: 10800<\/code><br \/>\n<code>Microseconds: 0<\/code><\/p>\n<p>or<\/p>\n<pre class=\"lang:default decode:true \">from datetime import timedelta, date, datetime\r\n\r\ndelta = timedelta(weeks=2, days=2, hours=2)\r\nprint(delta)\r\n\r\ndelta2 = delta * 2\r\nprint(delta2)\r\n\r\nd = date(2019, 10, 4) + delta2\r\nprint(d)\r\n\r\ndt = datetime(2019, 10, 4, 14, 53) + delta2\r\nprint(dt)<\/pre>\n<p><code>16 days, 2:00:00<\/code><br \/>\n<code>32 days, 4:00:00<\/code><br \/>\n<code>2019-11-05<\/code><br \/>\n<code>2019-11-05 18:53:00<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Example<\/p>\n<pre class=\"lang:default decode:true\">from datetime import timedelta \r\ndelta = timedelta(weeks = 1, days = 7, hours = 11) \r\nprint(delta * 2)<\/pre>\n<p><code>28 days, 22:00:00<\/code><\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true\">from datetime import datetime \r\ndatetime1 = datetime(2019, 11, 27, 11, 27, 22) \r\ndatetime2 = datetime(2019, 11, 27, 0, 0, 0) \r\nprint(datetime1 - datetime2)<\/pre>\n<p><code>11:27:22<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>10. The <strong><code>datetime<\/code> <\/strong>module provides several methods to create a <strong><code>date<\/code> <\/strong>object. One of them is the <code>fromisoformat<\/code> method, which takes a date in the <b>YYYY-MM-DD<\/b> format compliant with the ISO 8601 standard.<\/p>\n<pre class=\"lang:default decode:true \">from datetime import date\r\n\r\nd = date.fromisoformat('2019-11-04')\r\nprint(d)<\/pre>\n<p><code>2019-11-04<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>11. Sometimes you may need to replace the year, month, or day with a different value. You can\u2019t do this with the year, month, and day attributes because they&#8217;re read-only. In this case, you can use the method named <strong><code>replace()<\/code><\/strong>.<\/p>\n<pre class=\"lang:default decode:true\">from datetime import date\r\n\r\nd = date(1991, 2, 5)\r\nprint(d)\r\n\r\nd = d.replace(year=1992, month=1, day=16)\r\nprint(d)<\/pre>\n<p><code>1991-02-05<\/code><br \/>\n<code>1992-01-16<\/code><\/p>\n<p>The <i>year<\/i>, <i>month<\/i>, and <i>day<\/i> parameters are optional. You can pass only one parameter to the <code>replace<\/code> method, e.g., <i>year<\/i>, or all three as in the example.<\/p>\n<p>&nbsp;<\/p>\n<p>12. What day of the week is it?<\/p>\n<p>The method called <strong><code>weekday()<\/code><\/strong> returns the day of the week as an integer, where 0 is Monday and 6 is Sunday.<\/p>\n<pre class=\"lang:default decode:true \">from datetime import date\r\n\r\nd = date(2019, 11, 4)\r\nprint(d.weekday())<\/pre>\n<p><code>0<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>13. The <code>time<\/code> module provides a function called <code>ctime<\/code>, which <b>converts the time in seconds since January 1, 1970 (Unix epoch) to a string<\/b>.<\/p>\n<pre class=\"lang:default decode:true \">import time\r\n\r\ntimestamp = 1572879180\r\nprint(time.ctime(timestamp))<\/pre>\n<p><code>Mon Nov 4 14:53:00 2019<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Exercise 1<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true \">from datetime import time\r\n\r\nt = time(14, 53)\r\nprint(t.strftime(\"%H:%M:%S\"))<\/pre>\n<p id=\"sol\"><code class=\"codep \">14:39:00<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Exercise 2<\/strong><\/p>\n<p>What is the output of the following snippet?<\/p>\n<pre class=\"lang:default decode:true \">from datetime import datetime\r\n\r\ndt1 = datetime(2020, 9, 29, 14, 41, 0)\r\ndt2 = datetime(2020, 9, 28, 14, 41, 0)\r\n\r\nprint(dt1 - dt2)<\/pre>\n<p id=\"sol2\"><code class=\"codep \">1 day, 0:00:00<\/code><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The\u00a0 datetime module provides classes for working with date and time.\u00a0Date and time have countless uses and it&#8217;s probably hard to find a production application that doesn&#8217;t use them.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6153"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=6153"}],"version-history":[{"count":20,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6153\/revisions"}],"predecessor-version":[{"id":6155,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6153\/revisions\/6155"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=6153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=6153"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=6153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}