Home >Technology peripherals >It Industry >Understanding Python Date and Time, 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 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 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):
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
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():
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
The localtime() function returns a struct_time in local time from time expressed in seconds since the beginning of the epoch:
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
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:
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
The strftime() method converts a struct_time to a time string as specified by a given format argument:
Time string: Thu Apr <span>20 01:46:24 2023</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_tuple <span>= time_module.gmtime() </span>time_format <span>= "%y/%m/%d %I:%M:%S %p" </span> time_in_string <span>= time_module.strftime(time_format, time_tuple) </span> <span>print("Time expressed as formatted string:", time_in_string)</span>
The sleep() function delays the execution of a thread for a specified number of seconds:
Time expressed as formatted string: <span>23/04/20 04:40:04 PM</span>
Here’s the output of the code above:
<span>import time as time_module </span> <span>for i in range(5): </span> local_time <span>= time_module.localtime() </span> seconds <span>= local_time.tm_sec </span> <span>print(seconds) </span> time_module<span>.sleep(2)</span>
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 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.
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:
<span>49 </span><span>51 </span><span>53 </span><span>55 </span><span>57</span>
Here’s the output of the code above:
<span>from datetime import datetime </span> current_date_time <span>= datetime.now() </span><span>print(current_date_time)</span>
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:
<span>2023-04-20 13:47:02.362424</span>
Here’s the output of the code above:
<span>from datetime import date </span> current_date <span>= date.today() </span><span>print(current_date)</span>
The datetime module currently has six classes, each with different methods for manipulating date and time objects. The classes are listed as follows:
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:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
The date object constructor takes three integer arguments and should be within the specified range:
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.
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:
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
To get the current local date, use the date class today() and ctime() methods:
Time struct <span>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)</span>
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:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
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:
Time struct <span>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)</span>
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:
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
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:
Time string: Thu Apr <span>20 01:46:24 2023</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_tuple <span>= time_module.gmtime() </span>time_format <span>= "%y/%m/%d %I:%M:%S %p" </span> time_in_string <span>= time_module.strftime(time_format, time_tuple) </span> <span>print("Time expressed as formatted string:", time_in_string)</span>
To extract the year, month and day from a date object, use the .year, .month, and .day attributes of the date class:
Time expressed as formatted string: <span>23/04/20 04:40:04 PM</span>
Here’s the output of the code above:
<span>import time as time_module </span> <span>for i in range(5): </span> local_time <span>= time_module.localtime() </span> seconds <span>= local_time.tm_sec </span> <span>print(seconds) </span> time_module<span>.sleep(2)</span>
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:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
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:
When arguments that are out of range are passed to the constructor, it raises a ValueError.
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:
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
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:
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
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:
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
To extract values for hours, minutes, seconds and microseconds, use the hour, minute, second, and microsecond attributes of the time object:
Time string: Thu Apr <span>20 01:46:24 2023</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_tuple <span>= time_module.gmtime() </span>time_format <span>= "%y/%m/%d %I:%M:%S %p" </span> time_in_string <span>= time_module.strftime(time_format, time_tuple) </span> <span>print("Time expressed as formatted string:", time_in_string)</span>
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:
Time expressed as formatted string: <span>23/04/20 04:40:04 PM</span>
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:
A ValueError is raised if arguments are out of range.
To create a datetime object, import the datetime class from the datetime module and pass the following arguments:
<span>import time as time_module </span> <span>for i in range(5): </span> local_time <span>= time_module.localtime() </span> seconds <span>= local_time.tm_sec </span> <span>print(seconds) </span> time_module<span>.sleep(2)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
To get the current local date and time, use the now() method of the datetime class:
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
To create a datetime object from a date time string in ISO 8601 format, use the fromisoformat() method of the datetime class:
Time struct <span>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)</span>
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:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
A datetime object offers the following attributes: year, month, day, hour, minute, second, microsecond, tzinfo and fold. The attributes can be accessed as follows:
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
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.
A timedelta object represents a duration, the difference between two dates or times.
A timedelta object can be instantiated as follows:
Time string: Thu Apr <span>20 01:46:24 2023</span>
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:
All arguments should fall within the following range as specified in the docs:
An OverFlowError is raised if arguments are outside the normalized days range.
To create a timedelta object, import the timedelta class from the datetime module. Pass the appropriate arguments to the constructor function:
<span>import time as time_module </span> time_tuple <span>= time_module.gmtime() </span>time_format <span>= "%y/%m/%d %I:%M:%S %p" </span> time_in_string <span>= time_module.strftime(time_format, time_tuple) </span> <span>print("Time expressed as formatted string:", time_in_string)</span>
Here’s the output of the code above:
Time expressed as formatted string: <span>23/04/20 04:40:04 PM</span>
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.
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:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
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 more detailed table with format code can be found in the Python docs.
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:
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
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:
Time struct <span>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)</span>
A string format code is passed as an argument to strptime() method to format date.
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:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
Here’s the output of the code above:
Time struct <span>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)</span>
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).
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
Here’s the output of the code above:
Time string: Thu Apr <span>20 01:46:24 2023</span>
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.
<span>import time as time_module </span> time_tuple <span>= time_module.gmtime() </span>time_format <span>= "%y/%m/%d %I:%M:%S %p" </span> time_in_string <span>= time_module.strftime(time_format, time_tuple) </span> <span>print("Time expressed as formatted string:", time_in_string)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_seconds <span>= time_module.time() </span><span>print("Time in sceconds from epoch", time_in_seconds)</span>
In the code snippet above, we’ve created two timedelta objects, time_delta1 and time_delta2, and calculated the difference between them.
Time <span>in sceconds from epoch 1680712853.0801558</span>
Here’s the output of the code above:
<span>import time as time_module </span> utc_time_in_seconds <span>= time_module.gmtime() </span><span>print("Time struct in UTC", utc_time_in_seconds)</span>
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.
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.
Time struct <span>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)</span>
Here’s the output for the code above:
<span>import time as time_module </span> local_time <span>= time_module.localtime() </span><span>print("Time struct in local time:", local_time)</span>
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.
Time struct <span>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)</span>
Here’s the output of the code above:
<span>import time as time_module </span> time_in_secs <span>= 1678671984.939945 </span> time_string <span>= time_module.ctime(time_in_secs) </span><span>print("Time string: ",time_string)</span>
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.
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.
In Python, you can convert a string to a date using the datetime module’s strptime() function. This function takes two arguments: the string you want to convert and a format code that matches the string’s date format. For example, if you have a date string “2022-03-01” in the format “YYYY-MM-DD”, you can convert it to a date like this:
from datetime import datetime
date_string = "2022-03-01"
date_object = datetime.strptime(date_string, "%Y-%m-%d")
Python’s datetime module provides the datetime.now() function, which returns the current date and time. Here’s how you can use it:
from datetime import datetime
current_datetime = datetime.now()
print(current_datetime)
Python’s datetime module provides the strftime() function, which you can use to format a date. This function takes a format code as an argument and returns a string representing the date in the specified format. For example, to format a date in the “YYYY-MM-DD” format, you can do this:
from datetime import datetime
current_datetime = datetime.now()
formatted_date = current_datetime.strftime("%Y-%m-%d")
print(formatted_date)
Python’s datetime module provides the timedelta class, which you can use to add or subtract a certain number of days from a date. Here’s how you can use it:
from datetime import datetime, timedelta
current_date = datetime.now()
new_date = current_date timedelta(days=5)
print(new_date)
In Python, you can compare two dates using comparison operators like , ==, !=, =. Here’s an example:
from datetime import datetime
date1 = datetime(2022, 3, 1)
date2 = datetime(2022, 4, 1)
if date1 print("date1 is earlier than date2")
Python’s datetime module provides the weekday() function, which returns the day of the week as an integer (where Monday is 0 and Sunday is 6). Here’s how you can use it:
from datetime import datetime
current_date = datetime.now()
day_of_week = current_date.weekday()
print(day_of_week)
In Python, you can convert a date to a timestamp using the timestamp() function of the datetime module. Here’s an example:
from datetime import datetime
current_date = datetime.now()
timestamp = current_date.timestamp()
print(timestamp)
Python’s dateutil module provides the parser.parse() function, which can parse a date from a string. Here’s how you can use it:
from dateutil import parser
date_string = "2022-03-01"
date_object = parser.parse(date_string)
print(date_object)
Python’s datetime module provides the datetime.now() function, which returns the current date and time. If you only want the time, you can use the time() function like this:
from datetime import datetime
current_time = datetime.now().time()
print(current_time)
In Python, you can convert a timestamp to a date using the datetime.fromtimestamp() function. Here’s an example:
from datetime import datetime
timestamp = 1646332800
date_object = datetime.fromtimestamp(timestamp)
print(date_object)
The above is the detailed content of Understanding Python Date and Time, with Examples. For more information, please follow other related articles on the PHP Chinese website!