reCAPTCHA WAF Session Token
Programming Languages

Understanding Python Date and Time, with Examples — SitePoint

In this article, we’ll explore how to use date and time in Python. We’ll see real-life examples of working with date and time using the Python datetime and time modules.

Working with times and dates is inevitable when building real-life projects, and there are many use cases for them. Thankfully, Python has a couple of modules that make it easy to work with dates and times across different timezones.

The code for this tutorial can be found on GitHub.

Contents:

  1. The time Module
  2. The datetime Module
  3. Getting the Current Date and Time in Python
  4. Getting the Current Date in Python
  5. The datetime Module Classes
  6. The date Class
  7. The time Class
  8. The datetime Class
  9. The timedelta Class
  10. Python datetime Formatting
  11. Working with timedelta

The time Module

The Python time module is for performing time-related operations. We’ll now highlight some of the most commonly used functions in the time module, with examples.

The time() function

The time() function returns the current time in seconds since the beginning of a set epoch as a floating point number. The epoch that’s used starts in January 1, 1970, 00:00:00 (UTC):

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module

time_in_seconds <span class="token operator">=</span> time_module<span class="token punctuation">.</span>time<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time in sceconds from epoch"</span><span class="token punctuation">,</span> time_in_seconds<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time <span class="token keyword">in</span> sceconds from epoch <span class="token number">1680712853.0801558</span></code>

The gmtime() function

The gmtime() function returns a struct_time in UTC from time expressed in seconds since the beginning of the epoch. A struct_time is a type of time value sequence with a named tuple interface returned by gmtime(), localtime(), and strptime():

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module

utc_time_in_seconds <span class="token operator">=</span> time_module<span class="token punctuation">.</span>gmtime<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time struct in UTC"</span><span class="token punctuation">,</span> utc_time_in_seconds<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time struct <span class="token keyword">in</span> UTC: time.struct_time<span class="token punctuation">(</span>tm_year<span class="token operator">=</span><span class="token number">2023</span>, <span class="token assign-left variable">tm_mon</span><span class="token operator">=</span><span class="token number">3</span>, <span class="token assign-left variable">tm_mday</span><span class="token operator">=</span><span class="token number">16</span>, <span class="token assign-left variable">tm_hour</span><span class="token operator">=</span><span class="token number">14</span>, <span class="token assign-left variable">tm_min</span><span class="token operator">=</span><span class="token number">47</span>, <span class="token assign-left variable">tm_sec</span><span class="token operator">=</span><span class="token number">28</span>, <span class="token assign-left variable">tm_wday</span><span class="token operator">=</span><span class="token number">3</span>, <span class="token assign-left variable">tm_yday</span><span class="token operator">=</span><span class="token number">75</span>, <span class="token assign-left variable">tm_isdst</span><span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span></code>

The localtime() function

The localtime() function returns a struct_time in local time from time expressed in seconds since the beginning of the epoch:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module

local_time <span class="token operator">=</span> time_module<span class="token punctuation">.</span>localtime<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time struct in local time:"</span><span class="token punctuation">,</span> local_time<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time struct <span class="token keyword">in</span> <span class="token builtin class-name">local</span> time: time.struct_time<span class="token punctuation">(</span>tm_year<span class="token operator">=</span><span class="token number">2023</span>, <span class="token assign-left variable">tm_mon</span><span class="token operator">=</span><span class="token number">4</span>, <span class="token assign-left variable">tm_mday</span><span class="token operator">=</span><span class="token number">20</span>, <span class="token assign-left variable">tm_hour</span><span class="token operator">=</span><span class="token number">15</span>, <span class="token assign-left variable">tm_min</span><span class="token operator">=</span><span class="token number">46</span>, <span class="token assign-left variable">tm_sec</span><span class="token operator">=</span><span class="token number">15</span>, <span class="token assign-left variable">tm_wday</span><span class="token operator">=</span><span class="token number">3</span>, <span class="token assign-left variable">tm_yday</span><span class="token operator">=</span><span class="token number">75</span>, <span class="token assign-left variable">tm_isdst</span><span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span></code>

The ctime() function

The ctime() method converts time in seconds from the beginning of the epoch to a string format. If no arguments are passed to the function, it returns a time string for the current time in seconds:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module

time_in_secs <span class="token operator">=</span> <span class="token number">1678671984.939945</span>  

time_string <span class="token operator">=</span> time_module<span class="token punctuation">.</span>ctime<span class="token punctuation">(</span>time_in_secs<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time string: "</span><span class="token punctuation">,</span>time_string<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time string: Thu Apr <span class="token number">20</span> 01:46:24 <span class="token number">2023</span></code>

The strftime() function

The strftime() method converts a struct_time to a time string as specified by a given format argument:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module

time_tuple <span class="token operator">=</span> time_module<span class="token punctuation">.</span>gmtime<span class="token punctuation">(</span><span class="token punctuation">)</span>
time_format <span class="token operator">=</span> <span class="token string">"%y/%m/%d %I:%M:%S %p"</span>

time_in_string <span class="token operator">=</span> time_module<span class="token punctuation">.</span>strftime<span class="token punctuation">(</span>time_format<span class="token punctuation">,</span> time_tuple<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time expressed as formatted string:"</span><span class="token punctuation">,</span> time_in_string<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time expressed as formatted string: <span class="token number">23</span>/04/20 04:40:04 PM</code>

The sleep() function

The sleep() function delays the execution of a thread for a specified number of seconds:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">import</span> time <span class="token keyword">as</span> time_module 

<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    local_time <span class="token operator">=</span> time_module<span class="token punctuation">.</span>localtime<span class="token punctuation">(</span><span class="token punctuation">)</span>
    seconds <span class="token operator">=</span> local_time<span class="token punctuation">.</span>tm_sec
    <span class="token keyword">print</span><span class="token punctuation">(</span>seconds<span class="token punctuation">)</span>
    time_module<span class="token punctuation">.</span>sleep<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span></code>

Here’s the output of the code above:

In the code above, the number 2 is passed in as an argument of the sleep() function, which causes the loop to delay two seconds before execution. The numbers that are output validate our code.

The datetime Module

The datetime module supplies classes for manipulating dates and times.

These classes are essential for easy manipulation, extraction, and output formatting of time intervals, times and dates. Ordinarily, date and time are not considered data types in Python, but they are date and time objects of the datetime module classes. Datetime classes also have different methods available for handling date and time objects.

Getting the Current Date and Time in Python

To get the current date and time, import the datetime class from the datetime module. The datetime class has a method, now(), which returns the current date and time:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span>  datetime  <span class="token keyword">import</span>  datetime

current_date_time <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>current_date_time<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash"><span class="token number">2023</span>-04-20 <span class="token number">13</span>:47:02.362424</code>

Getting the Current Date in Python

To get the current date, import the date class from the datetime module. The date class has a method, today(), which returns the current date:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> date

current_date <span class="token operator">=</span> date<span class="token punctuation">.</span>today<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>current_date<span class="token punctuation">)</span></code>

Here’s the output of the code above:

The datetime Module Classes

The datetime module currently has six classes, each with different methods for manipulating date and time objects. The classes are listed as follows:

  • date
  • time
  • datetime
  • timedelta
  • tzinfo
  • timezone

The date Class

A date object represents a date (year, month and day) in an idealized calendar — the current Gregorian calendar indefinitely extended in both directions.

A date object can be instantiated as follows:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>">datetime<span class="token punctuation">.</span>date<span class="token punctuation">(</span>year<span class="token punctuation">,</span> month<span class="token punctuation">,</span> day<span class="token punctuation">)</span></code>

The date object constructor takes three integer arguments and should be within the specified range:

  • MINYEAR MAXYEAR
  • 1
  • 1

In the code above, MINYEAR is 1 and MAXYEAR is 9999. The values represent the smallest and biggest year number allowed in a date or datetime object.

When the arguments are out of range, it throws a ValueError, and non-integer arguments throw a TypeError.

Example: Create a date object

To create a date object, import the date class from the datetime module, and pass arguments for year, month and day into the date constructor. The arguments must be integers and within the specified range:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> date

mydate <span class="token operator">=</span> date<span class="token punctuation">(</span><span class="token number">2023</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'The date is: '</span><span class="token punctuation">,</span> mydate<span class="token punctuation">)</span></code>

Here’s the output of the code above:

Example: Get the current date

To get the current local date, use the date class today() and ctime() methods:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> date

current_date <span class="token operator">=</span> date<span class="token punctuation">.</span>today<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>current_date<span class="token punctuation">.</span>ctime<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span></code>

The today() method will return a local date, while the ctime() method renders the date as a string.
Here’s the output of the code above:

Example: Create the date from ISO format

A date object can be created from a date string in ISO 8601 format. Use the fromisoformat() method of the date class to do this:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> date

iso_date <span class="token operator">=</span> date<span class="token punctuation">.</span>fromisoformat<span class="token punctuation">(</span><span class="token string">'2023-04-20'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Date from ISO format: "</span><span class="token punctuation">,</span> iso_date<span class="token punctuation">)</span></code>

Note: ISO 8601 is a standardized format for presenting dates and time without creating confusion across different regions or timezones. ISO 8601 takes the format YYYY-MM-DD.

Here’s the output of the code above:

<code class="language-bash">Date from ISO format:  <span class="token number">2023</span>-04-20</code>

Example: Create date object from string

To create a date object, pass a date string and corresponding format to the strptime() method. Extract the date by using the date() method of the returned datetime object:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

datetime_object <span class="token operator">=</span> datetime<span class="token punctuation">.</span>strptime<span class="token punctuation">(</span><span class="token string">"20/04/23"</span><span class="token punctuation">,</span> <span class="token string">"%d/%m/%y"</span><span class="token punctuation">)</span>
date_object <span class="token operator">=</span> datetime_object<span class="token punctuation">.</span>date<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Date from string:"</span><span class="token punctuation">,</span> date_object<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Date from string: <span class="token number">2023</span>-04-20</code>

Example: Get the year, month, day from the date object

To extract the year, month and day from a date object, use the .year, .month, and .day attributes of the date class:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> date

current_date <span class="token operator">=</span> date<span class="token punctuation">.</span>today<span class="token punctuation">(</span><span class="token punctuation">)</span>

year <span class="token operator">=</span> current_date<span class="token punctuation">.</span>year
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"The year is: "</span><span class="token punctuation">,</span> year<span class="token punctuation">)</span>

month <span class="token operator">=</span> current_date<span class="token punctuation">.</span>month
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"The month is: "</span><span class="token punctuation">,</span> month<span class="token punctuation">)</span>

day <span class="token operator">=</span> current_date<span class="token punctuation">.</span>day
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"The day is: "</span><span class="token punctuation">,</span> day<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">The year is: <span class="token number">2023</span>
The month is: <span class="token number">4</span>
The day is: <span class="token number">20</span></code>

The time Class

A time object represents a (local) time of day, independent of any particular day, and subject to adjustment via a tzinfo object.

A date object can be instantiated as follows:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>">datetime<span class="token punctuation">.</span>time<span class="token punctuation">(</span>hour<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> minute<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> second<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> microsecond<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> tzinfo<span class="token operator">=</span><span class="token boolean">None</span><span class="token punctuation">)</span></code>

The time object can be instantiated without any arguments. All arguments are optional with a default value of 0, except tzinfo, which is None. All arguments must be integers within a specified range, while the tzinfo argument should be an instance of the tzinfo subclass:

  • 0
  • 0
  • 0
  • 0

When arguments that are out of range are passed to the constructor, it raises a ValueError.

Example: Create a time object

To create a time object, import the time class from the datetime module. Pass arguments for hours, minutes, seconds, microseconds and tzinfo. Remember that all arguments are optional, so when no argument is passed to the constructor, the time object returns 00:00:00:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> time

my_time <span class="token operator">=</span> time<span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"My time is: "</span><span class="token punctuation">,</span> my_time<span class="token punctuation">)</span></code>

Here’s the output of the code above:

Example: Create time from ISO format

A time object can be created from a time string in ISO 8601 format. Use the fromisoformat() method of the time class to do this:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> time

iso_time <span class="token operator">=</span> time<span class="token punctuation">.</span>fromisoformat<span class="token punctuation">(</span><span class="token string">'12:45:12'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'The time says: '</span><span class="token punctuation">,</span> iso_time<span class="token punctuation">)</span></code>

Here’s the output of the code above:

Example: Create time object from string

To create a time object, pass a date string and corresponding format to the strptime() method. Extract the time by using the time() method of the returned datetime object:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

datetime_object <span class="token operator">=</span> datetime<span class="token punctuation">.</span>strptime<span class="token punctuation">(</span><span class="token string">"20 Apr, 2023 13:50:30"</span><span class="token punctuation">,</span> <span class="token string">"%d %b, %Y %H:%M:%S"</span><span class="token punctuation">)</span>
time_object <span class="token operator">=</span> datetime_object<span class="token punctuation">.</span>time<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Time from string:"</span><span class="token punctuation">,</span> time_object<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time from string: <span class="token number">13</span>:50:30</code>

Example: Get hours, minutes, seconds and microseconds from the time object

To extract values for hours, minutes, seconds and microseconds, use the hour, minute, second, and microsecond attributes of the time object:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> time

new_time <span class="token operator">=</span> time<span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">50</span><span class="token punctuation">,</span> <span class="token number">569230</span><span class="token punctuation">)</span>

hour <span class="token operator">=</span> new_time<span class="token punctuation">.</span>hour
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Hours: '</span><span class="token punctuation">,</span>hour<span class="token punctuation">)</span>

minute <span class="token operator">=</span> new_time<span class="token punctuation">.</span>minute
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Minutes: '</span><span class="token punctuation">,</span> minute<span class="token punctuation">)</span>

second <span class="token operator">=</span> new_time<span class="token punctuation">.</span>second
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Seconds: '</span><span class="token punctuation">,</span> second<span class="token punctuation">)</span>

microsecond <span class="token operator">=</span> new_time<span class="token punctuation">.</span>microsecond
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Microseconds: '</span><span class="token punctuation">,</span> microsecond<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Hours: <span class="token number">7</span>
Minutes: <span class="token number">20</span>
Seconds: <span class="token number">50</span>
Microseconds: <span class="token number">569230</span></code>

The datetime Class

A datetime object is a single object containing all the information from a date object and a time object.

A datetime object can be instantiated as follows:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>">datetime<span class="token punctuation">.</span>datetime<span class="token punctuation">(</span>year<span class="token punctuation">,</span> month<span class="token punctuation">,</span> day<span class="token punctuation">,</span> hour<span class="token punctuation">,</span> minute<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> second<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> microsecond<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> tzinfo<span class="token operator">=</span><span class="token boolean">None</span><span class="token punctuation">)</span></code>

The datetime constructor requires the year, month and day arguments. The tzinfo default is None or an instance of the tzinfo subclass. The time arguments are optional, but the arguments must be integers and within range:

  • MINYEAR
  • 1
  • 1
  • 0
  • 0
  • 0
  • 0

A ValueError is raised if arguments are out of range.

Example: Create a datetime object

To create a datetime object, import the datetime class from the datetime module and pass the following arguments:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

dt <span class="token operator">=</span> datetime<span class="token punctuation">(</span><span class="token number">2023</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">38</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">345389</span><span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">The <span class="token function">date</span> <span class="token function">time</span> is: <span class="token number">2023</span>-04-20 <span class="token number">10</span>:38:10.345389</code>

Example: Get the current local date and time

To get the current local date and time, use the now() method of the datetime class:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Current locate date time is: '</span><span class="token punctuation">,</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Current <span class="token function">locate</span> <span class="token function">date</span> <span class="token function">time</span> is: <span class="token number">2023</span>-04-20 <span class="token number">10</span>:50:08.944232</code>

Example: Create date time from ISO format

To create a datetime object from a date time string in ISO 8601 format, use the fromisoformat() method of the datetime class:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

iso_dt <span class="token operator">=</span> datetime<span class="token punctuation">.</span>fromisoformat<span class="token punctuation">(</span><span class="token string">'2023-04-20 11:25:30.983023'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Date time from ISO is: '</span><span class="token punctuation">,</span> iso_dt<span class="token punctuation">)</span></code>

Note: if the date string argument passed into the fromisoformat() method isn’t a valid ISO format string, a ValueError exception is raised. The date output here is quite similar to the result obtain from datetime.now().

Here’s the output of the code above:

<code class="language-bash">Date <span class="token function">time</span> from ISO is: <span class="token number">2023</span>-04-20 <span class="token number">11</span>:25:30.983023</code>

Example: Get date and time attributes from the datetime object

A datetime object offers the following attributes: year, month, day, hour, minute, second, microsecond, tzinfo and fold. The attributes can be accessed as follows:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

new_dt <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span>

year <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>year
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Year: '</span><span class="token punctuation">,</span> year<span class="token punctuation">)</span>

month <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>month
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Month: '</span><span class="token punctuation">,</span> month<span class="token punctuation">)</span>

day <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>day
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Day: '</span><span class="token punctuation">,</span> day<span class="token punctuation">)</span>

hour <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>hour
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Hours: '</span><span class="token punctuation">,</span> hour<span class="token punctuation">)</span>

minute <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>minute
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Minutes: '</span><span class="token punctuation">,</span> minute<span class="token punctuation">)</span>

second <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>second
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Seconds: '</span><span class="token punctuation">,</span> second<span class="token punctuation">)</span>

microsecond <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>microsecond
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Microseconds: '</span><span class="token punctuation">,</span> microsecond<span class="token punctuation">)</span>

tz_info <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>tzinfo
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Timezone info: '</span><span class="token punctuation">,</span> tz_info<span class="token punctuation">)</span>

fold <span class="token operator">=</span> new_dt<span class="token punctuation">.</span>fold
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Fold: '</span><span class="token punctuation">,</span> fold<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Year: <span class="token number">2023</span>
Month: <span class="token number">4</span>
Day: <span class="token number">20</span>
Hours: <span class="token number">12</span>
Minutes: <span class="token number">42</span>
Seconds: <span class="token number">15</span>
Microseconds: <span class="token number">794955</span>
Timezone info: None
Fold: O</code>

Note: the default attribute value for tzinfo is None, because there’s no object argument passed, and fold will return 0 by default. For more on the fold attribute (which was introduced in Python version 3.6), see the docs.

The timedelta Class

A timedelta object represents a duration, the difference between two dates or times.

A timedelta object can be instantiated as follows:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>">datetime<span class="token punctuation">.</span>timedelta<span class="token punctuation">(</span>days<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> seconds<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> microseconds<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> milliseconds<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> minutes<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> hours<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> weeks<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span></code>

All arguments are optional, with a default value of 0. Integers or floats, positive or negative numbers are valid arguments for the constructor.

Arguments are converted as follows:

  • A millisecond is converted to 1000 microseconds.
  • A minute is converted to 60 seconds.
  • An hour is converted to 3600 seconds.
  • A week is converted to 7 days.

All arguments should fall within the following range as specified in the docs:

  • 0 1000000
  • 0 3600*24 (the number of seconds in one day)
  • -999999999 999999999

An OverFlowError is raised if arguments are outside the normalized days range.

Example: Create a timedelta object

To create a timedelta object, import the timedelta class from the datetime module. Pass the appropriate arguments to the constructor function:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> timedelta

td <span class="token operator">=</span> timedelta<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">4300</span><span class="token punctuation">,</span> <span class="token number">3000</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Time Delta: '</span><span class="token punctuation">,</span> td<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Time Delta: <span class="token number">31</span> days, <span class="token number">5</span>:12:33.004300</code>

Python datetime Formatting

Date and time formats differ from region to region and country to country. It’s because of these differences in date and time formats that the ISO 8601 format was introduced, as a way to standardize date and time.
However, there may be a need to format date and time in a particular way based on a country or region.

Formatting datetime with the strftime() method

Datetime formatting can be done with the strftime() method. The strftime() method is an instance method of time, date and datetime classes, which means we have to create a date, time or datetime object to apply the method. The method takes a given format code as an argument, and returns a string representing time, date or datetime from in the desired format.

The method signature looks like this:

Usually a string format code is passed as an argument to strftime() method to format date. Some of the format codes are as follows:

  • %a: weekday abbreviated name — such as Sun, Mon, etc.
  • %b: month as abbreviated name — such as Jan, Feb, etc.
  • %y: year without century as a zero-padded decimal number — such as 00, 01, 02, etc.

A more detailed table with format code can be found in the Python docs.

Example: Format date and time in a datetime object

Just like in the previous examples, we can pass an argument of the format string of the desired date and time output to the strftime() method:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

date_time <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span>

formatted_date_time <span class="token operator">=</span> date_time<span class="token punctuation">.</span>strftime<span class="token punctuation">(</span><span class="token string">"%d %B %Y, %H:%M:%S"</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Formatted date and time:"</span><span class="token punctuation">,</span> formatted_date_time<span class="token punctuation">)</span>

formatted_date_time_2 <span class="token operator">=</span> date_time<span class="token punctuation">.</span>strftime<span class="token punctuation">(</span><span class="token string">"%A, %d %B %Y, %I:%M %p"</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Formatted date and time in 12-hour clock:"</span><span class="token punctuation">,</span> formatted_date_time_2<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Formatted <span class="token function">date</span> and time: <span class="token number">20</span> April <span class="token number">2023</span>, <span class="token number">11</span>:11:40
Formatted <span class="token function">date</span> and <span class="token function">time</span> <span class="token keyword">in</span> <span class="token number">12</span>-hour clock: Thursday, <span class="token number">20</span> April <span class="token number">2023</span>, <span class="token number">11</span>:11 AM</code>

Formatting datetime with the strptime() method

Unlike strftime(), the strptime() is a datetime class method, which means it can be used without creating an object of the class. The method returns a datetime object from a given date string and format.

The method signature looks like this:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>">strptime<span class="token punctuation">(</span>date_string<span class="token punctuation">,</span> <span class="token builtin">format</span><span class="token punctuation">)</span></code>

A string format code is passed as an argument to strptime() method to format date.

Example: String to datetime object

To create a datetime object, we’ll pass two arguments to the strptime() method, a date string and a corresponding format. A ValueError is raised when the date string doesn’t match the provided format:

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime

date_string <span class="token operator">=</span> <span class="token string">"April 20, 23 12:12:20"</span>
dt_format <span class="token operator">=</span> <span class="token string">"%B %d, %y %H:%M:%S"</span>

datetime_from_string <span class="token operator">=</span> datetime<span class="token punctuation">.</span>strptime<span class="token punctuation">(</span>date_string<span class="token punctuation">,</span> dt_format<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Datetime from string:"</span><span class="token punctuation">,</span> datetime_from_string<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Datetime from string: <span class="token number">2023</span>-04-20 <span class="token number">12</span>:12:20</code>

Working with timedelta

The timedelta class in Python is used for calculating the difference between dates, calculating time differences between specific dates, and also performing other calculations using specific units of time (such as weeks or hours).

Example: Calculate a future date

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime<span class="token punctuation">,</span> timedelta

date_now <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Today's date:"</span><span class="token punctuation">,</span> date_now<span class="token punctuation">)</span>

future_date <span class="token operator">=</span> date_now <span class="token operator">+</span> timedelta<span class="token punctuation">(</span>days<span class="token operator">=</span><span class="token number">7</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Future date is:"</span><span class="token punctuation">,</span> future_date<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Today's date: <span class="token number">2023</span>-04-20 <span class="token number">15</span>:50:43.415319
Future <span class="token function">date</span> is: <span class="token number">2023</span>-04-27 <span class="token number">15</span>:50:43.415319</code>

From the example above, we first get a current local date and time and a timedelta object of seven days. Because timedelta supports operations like addition, we add the datetime object and timedelta object to get a future day in seven days. If our current date is 2023-04-20, in seven days the date will be 2023-04-27.

Example: Calculate the difference between two timedelta objects

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> timedelta

time_delta1 <span class="token operator">=</span> timedelta<span class="token punctuation">(</span>days<span class="token operator">=</span><span class="token number">23</span><span class="token punctuation">,</span> hours<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> minutes<span class="token operator">=</span><span class="token number">20</span><span class="token punctuation">)</span>
time_delta2 <span class="token operator">=</span> timedelta<span class="token punctuation">(</span>days<span class="token operator">=</span><span class="token number">15</span><span class="token punctuation">,</span> seconds<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> microseconds<span class="token operator">=</span><span class="token number">123</span><span class="token punctuation">,</span> milliseconds<span class="token operator">=</span><span class="token number">234566</span><span class="token punctuation">,</span> minutes<span class="token operator">=</span><span class="token number">5</span><span class="token punctuation">,</span> hours<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>

result <span class="token operator">=</span> time_delta1 <span class="token operator">-</span> time_delta2

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Difference between two timedelta objects:"</span><span class="token punctuation">,</span> result<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Difference between two timedelta objects: <span class="token number">7</span> days, <span class="token number">22</span>:11:03.433877</code>

In the code snippet above, we’ve created two timedelta objects, time_delta1 and time_delta2, and calculated the difference between them.

Example: Calculate the sum of two timedelta objects

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> timedelta

time_delta1 <span class="token operator">=</span> timedelta<span class="token punctuation">(</span>days <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">,</span> hours <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">,</span> seconds <span class="token operator">=</span> <span class="token number">33</span><span class="token punctuation">,</span> weeks<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
time_delta2 <span class="token operator">=</span> timedelta<span class="token punctuation">(</span>days <span class="token operator">=</span> <span class="token number">4</span><span class="token punctuation">,</span> hours <span class="token operator">=</span> <span class="token number">11</span><span class="token punctuation">,</span> minutes <span class="token operator">=</span> <span class="token number">4</span><span class="token punctuation">,</span> seconds <span class="token operator">=</span> <span class="token number">54</span><span class="token punctuation">)</span>

result <span class="token operator">=</span> time_delta1 <span class="token operator">+</span> time_delta2

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Sum of two delta objects:"</span><span class="token punctuation">,</span> result<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Sum of two delta objects: <span class="token number">20</span> days, <span class="token number">12</span>:05:27</code>

As seen above, the timedelta objects support addition operation, and the result is output to the console. Timedelta objects support operations like subtraction, multiplication, and division.

Working with Timezones

The use of timezones is necessary if we want to create aware date and time objects. An aware time or date object includes information on the timezone. It’s also important for displaying time or date objects in relation to a particular region.

zoneinfo is a built-in Python module for working with timezones.

Example: Create a datetime object with timezone information

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime
<span class="token keyword">from</span> zoneinfo <span class="token keyword">import</span> ZoneInfo

tz <span class="token operator">=</span> ZoneInfo<span class="token punctuation">(</span><span class="token string">'Africa/Accra'</span><span class="token punctuation">)</span>
date_time_object <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span>tz<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Timezone information"</span><span class="token punctuation">,</span> date_time_object<span class="token punctuation">.</span>tzinfo<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Timezone code"</span><span class="token punctuation">,</span> date_time_object<span class="token punctuation">.</span>tzname<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span></code>

Here’s the output for the code above:

<code class="language-bash">Timezone information: Africa/Accra
Timezone code: GMT</code>

First, we import the datetime class from the datetime module and ZoneInfo from the zoneinfo module. We create a ZoneInfo object and then a datetime object, but this time we pass the timezone object tz to the now() method.

When we check the value of the tzinfo attribute, it returns the name of the timezone Africa/Accra, not None.

Example: Convert a datetime object from one timezone to another

<code class="language- <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1940"  title="Python"   target="_blank" >python</a>"><span class="token keyword">from</span> datetime <span class="token keyword">import</span> datetime
<span class="token keyword">from</span> zoneinfo <span class="token keyword">import</span> ZoneInfo

accra_timezone <span class="token operator">=</span> ZoneInfo<span class="token punctuation">(</span><span class="token string">'Africa/Accra'</span><span class="token punctuation">)</span>
accra_datetime <span class="token operator">=</span> datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span>accra_timezone<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Current date time in Accra:"</span><span class="token punctuation">,</span> accra_datetime<span class="token punctuation">)</span>


new_york_timezone <span class="token operator">=</span> ZoneInfo<span class="token punctuation">(</span><span class="token string">'America/New_York'</span><span class="token punctuation">)</span>
new_york_datetime <span class="token operator">=</span> accra_datetime<span class="token punctuation">.</span>astimezone<span class="token punctuation">(</span>new_york_timezone<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Current date time in New York:"</span><span class="token punctuation">,</span> new_york_datetime<span class="token punctuation">)</span></code>

Here’s the output of the code above:

<code class="language-bash">Current <span class="token function">date</span> <span class="token function">time</span> <span class="token keyword">in</span> Accra <span class="token number">2023</span>-04-20 <span class="token number">10</span>:42:02.476541+00:00
Current <span class="token function">date</span> <span class="token function">time</span> <span class="token keyword">in</span> New York <span class="token number">2023</span>-04-20 06:42:02.476541-04:00</code>

To convert between timezones, we use the astimezone() method of the datetime object, passing in a new timezone object. The astimezone() returns a new datetime object with updated timezone information.

Conclusion

Keeping track of time is an important aspect of our daily lives, and this also translates into programming. When we build real-world projects, there’s always the need to keep time logs for user activities like login and sign-out, among other use cases. It’s also important to put a time stamp on content generated online and to display time and date according to a user’s region or timezone.

To better manage times and dates in our programs or applications, Python provides the time and datetime modules. These modules have functions, classes and methods for managing time-related tasks. In this article, we’ve highlighted some commonly used functions and methods, providing examples of how they can be used.

The code for this tutorial can be found on GitHub.




Source link

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
WP Twitter Auto Publish Powered By : XYZScripts.com
SiteLock