SitePoint’s guide to understanding Python Date and Time, explained with examples

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:
– The time Module
– The datetime Module
– Getting the Current Date and Time in Python
– Getting the Current Date in Python
– The datetime Module Classes
– The date Class
– The time Class
– The datetime Class
– The timedelta Class
– Python datetime Formatting
– 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):

<pre><code>import time as time_module
time_in_seconds = time_module.time()
print("Time in seconds from epoch", time_in_seconds)</code></pre>

Here’s the output of the code above:
Time in seconds from epoch 1680712853.0801558

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():

<pre><code>import time as time_module
utc_time_in_seconds = time_module.gmtime()
print("Time struct in UTC", utc_time_in_seconds)</code></pre>

Here’s the output of the code above:
Time struct in UTC: time.struct_time(tm_year=2023, tm_mon=3, tm_mday=16, tm_hour=14, tm_min=47, tm_sec=28, tm_wday=3, tm_yday=75, tm_isdst=0)

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

<pre><code>import time as time_module
local_time = time_module.localtime()
print("Time struct in local time:", local_time)</code></pre>

Here’s the output of the code above:
Time struct in local time: time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=15, tm_min=46, tm_sec=15, tm_wday=3, tm_yday=75, tm_isdst=0)

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:

<pre><code>import time as time_module
time_in_secs = 1678671984.939945
time_string = time_module.ctime(time_in_secs)
print("Time string: ",time_string)</code></pre>

Here’s the output of the code above:
Time string: Thu Apr 20 01:46:24 2023

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

<pre><code>import time as time_module
time_tuple = time_module.gmtime()
time_format = "%y/%m/%d %I:%M:%S %p"
time_in_string = time_module.strftime(time_format, time_tuple)
print("Time expressed as formatted string:", time_in_string)</code></pre>

Here’s the output of the code above:
Time expressed as formatted string: 23/04/20 04:40:04 PM

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

<pre><code>import time as time_module
for i in range(5):
local_time = time_module.localtime()
seconds = local_time.tm_sec
print(seconds)
time_module.sleep(2)</code></pre>

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:

<pre><code>from datetime import datetime
current_date_time = datetime.now()
print(current_date_time)</code></pre>

Here’s the output of the code above:
2023-04-20 13:47:02.362424

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:

<pre><code>from datetime import date
current_date = date.today()
print(current_date)</code></pre>

Here’s the output of the code above:
2023-04-20

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:

datetime.date(year, month, day)

The date object constructor takes three integer arguments and should be within the specified range:
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year

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

Source link

Leave a Reply