This Python DateTime Tutorial explains how to handle the Time and DateTime using practical examples:
When we start learning how to code, we usually sit at our computer and run programs manually, which is fine. But to design complex systems, running tasks without direct supervision is usually indispensable.
Our computer’s clock can be used to schedule programs or tasks to run at specific times, dates, or intervals. However, it may be challenging to work directly with this clock due to time zones, daylight saving time, and date representation formats.
Python provides an easy way to remediate these challenges by providing two modules i.e. Time and DateTime. In this tutorial, we will examine Python Time and DateTime.
=> Read Through ALL Python Tutorials Here
Table of Contents:
Python Time and Datetime
VIDEO Tutorial: A Detailed Look at Python DateTime
Epoch
In Python, time and date are considered as a period of time from a starting point, called Epoch.
Wikipedia defined epoch as:
A date and time from which a computer measures system time.
Different OS, filesystems, and APIs use different epochs, but the most commonly used epoch, which is the UNIX epoch, defines the epoch as 12 AM on January 1, 1970.
The Time Module
Our computer’s system clock is complex if accessed and used directly. Python has the built-in time module that allows our Python programs to manipulate the system’s clock with ease.
This module has an awful lot of functions. But in this section, we shall look at the commonly used ones. If you would like to know more about the other functions, visit the Python Official Documentation.
#1) The time.time() Function
It returns the current time as a floating-point number of seconds since the epoch.
Example 1: Find the current time since the epoch
>>> import time >>> time.time() 1620106022.9683251
The code above was run on May 4, 2021, at 06:27 AM WAT, or 05:27 AM UTC. The return value defines how many seconds have elapsed since the Unix epoch.
NB: Your output will be different based on the date and time you run the code. However, you can set your computer’s system clock to this date and time in order to obtain approximately the same result.
This function can be used to find the time taken for a piece of code to execute. All we have to do is, just run the function before and after the execution of the code, and then find the difference between them.
Example 2: Find the time taken for a code to execute.
from time import time def sample_code(): # compute the square of the first 1000000 numbers for i in range(1, 1000000): x = i ** 2 if __name__ == '__main__': start_time = time() # record time before executing code sample_code() end_time = time() - start_time # compute time after execution of code print('Execution time: ', end_time)
Output:
#2) The time.sleep(t) function
The sleep() function pauses our program or thread running for a while. It takes in a number or fraction, t that represents the amount of time to wait in seconds, but doesn’t return any value.
Example 3: Suspend a program for 30 seconds
import time def suspend(): start_time = time.time() # record time before time.sleep(30) # pause the program for 30 seconds end_time = time.time() - start_time # evaluate time after print("Time slept is: ", round(end_time), "seconds") if __name__ == '__main__': suspend()
Output
This example shows how we can suspend a program for 30 seconds. We recorded the time before and after calling the sleep() function just to confirm the time taken while on pause. As expected, it took about 30 seconds.
NB: Here, we made it easy to read by using the round() function to round the resulting time taken to the nearest whole integer.
#3) time.localtime([secs])
The localtime method returns the local time as a time.struct_time object from the number of seconds elapsed since the epoch.
The method takes in an optional parameter representing the number of seconds to convert. If no argument or None is given, then the current time as returned by time.time() will be used.
Example 4: Get local time and its attributes
import time def get_localtime(): # seconds as returned by time.time() is used # since no attribute was passed lt = time.localtime() print("***STRUCT TIME OBJECT***") print(lt) print("\n***COMPLETE ATTRIBUTES***") # get a complete set of the object's attributes that starts with 'tm' for i in dir(lt): if i.startswith('tm'): print(i) if __name__ == '__main__': get_localtime()
Output
Notice the struct_time object returned above. Though it doesn’t show the attributes tm_gmtoff and tm_zone, they were made available from version 3.6 and can be retrieved as shown above.
Let’s break down these attributes below:
struct_time object
Index | Attribute | Field | Value |
---|---|---|---|
0 | tm_year | Year | 4-digit year, 2021 |
1 | tm_mon | Month | 1 to 12 |
2 | tm_mday | Day | 1 to 31 |
3 | tm_hour | Hour | 0 to 23 |
4 | tm_min | Minute | 0 to 59 |
5 | tm_sec | Second | 0 to 61 |
6 | tm_wday | Day of Week | 0 to 6. Monday is 0 |
7 | tm_yday | Day of Year | 1 to 366 |
8 | tm_isdst | Daylight savings | 0, 1 or -1 |
N/A | tm_zone | Timezone | WAT, EST,... |
N/A | tm_gmtoff | offset east of UTC in seconds | 3600,... |
These attributes can be accessed by their attribute names or indices. However, for tm_zone and tm_gmtoff, they don’t have any indices. Hence, it can be accessed only by attribute name.
#4) time.ctime([secs])
It converts the number of seconds since the epoch to a string representing local time in a readable format, for example; ‘Sun May 9 06:44:59 2021‘. If no secs or None is provided, then the current time as returned by time() is used. It is similar to time.asctime([localtime(secs)]).
Example 5: Return local time in a readable format.
>>> import time >>> time.ctime() 'Sun May 9 07:23:35 2021'
#5) time.strftime(format[, t])
It converts time, t as a tuple or struct_time object commonly returned by time.gmtime() or time.localtime() to a string following the format argument.
The first argument should be the format that the output string will adopt. Python has an awful lot of directives that can make up the format string. The table below shows the commonly used directives.
Directives that make up the format string
Directive | Description |
---|---|
%a | Locale’s abbreviated weekday name. |
%b | Locale’s abbreviated month name. |
%c | Locale’s appropriate date and time representation. |
%d | Day of the month as a decimal number [01,31]. |
%H | Hour (24-hour clock) as a decimal number [00,23]. |
%I | Hour (12-hour clock) as a decimal number [01,12]. |
%m | Month as a decimal number [01,12]. |
%M | Minute as a decimal number [00,59]. |
%p | Locale’s equivalent of either AM or PM. |
%S | Second as a decimal number [00,61]. |
%w | Weekday as a decimal number [0(Sunday),6]. |
%x | Locale’s appropriate date representation. |
%Y | Year with century as a decimal number. |
%Z | Time zone name (no characters if no time zone exists). |
Example 6: Format time similar to ctime(), using strftime()
import time def format_time(format, t): format_t = time.strftime(format, t) return format_t if __name__ == '__main__': # format time using directives as returned by time.ctime() format = '%a %b %d %H:%M:%S %Y' # get local time as struct_time object of current time t = time.localtime() print("Current time: ", format_time(format, t))
Output
The DateTime module
The DateTime module is used to work and display dates in a more convenient format. For example, say we want to find which date it will be 400 days from now, or what date was it 400 days ago, for cases like these, we use the DateTime module.
The DateTime module has many types and constants. Let’s see all of them using the dir() method
Example 7: Display all valid attributes of the DateTime module.
>>> import datetime >>> dir(datetime) ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
Constants
Looking at example 7, we can spot two constants that can be exported from the DateTime module i.e. MINYEAR and MAXYEAR. The former represents the smallest year decimal allowed in a date or DateTime object while the latter represents the largest year decimal.
Let’s verify their values in the example below.
Example 8: Verify values of the constants MINYEAR and MAXYEAR
>>> import datetime >>> datetime.MINYEAR 1 >>> datetime.MAXYEAR 9999
Available Types
From the example 7 above, the Available types or classes are; date, time, datetime, timedelta, tzinfo, and timezone.
Let’s examine each of these further.
#1) Class datetime.date
This class represents a date as; year, month, and day. Its date() constructor takes in three compulsory arguments which must follow the following ranges, else ValueError will be raised.
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days based on the given month and year.
The date class has many methods and attributes but the commonly used ones are.
datetime.date Common Attributes and Methods
Method & Attribute | Description |
---|---|
date.year | Represents the year between MINYEAR and MAXYEAR inclusively. |
date.day | Represents the day between 1 and the number of days in the given month of the given year. |
date.month | Represents the month between 1 and 12 inclusive. |
date.today() | Return the current local date as set by the computer's system clock. |
date.isoformat() | Returns a string representing the date in ISO 8601 format. That is, YYYY-MM-DD |
date.fromisoformat() | Returns a date object from ISO 8601 format. |
date.fromtimestamp(timestamp) | Takes in a timestamp, such as is returned by time.time() and return its local date correspondant. |
date.replace(self.year, self.month, self.day) | Replace year, month, or day of a date object |
date.isoweekday() | Return the day of the week from 1 which is Monday and 7 which is Sunday inclusive. |
date.ctime() | Returns a string represetning the date, same as time.ctime we saw in example 5 above |
date.strftime(format) | Return a string representing the date following a format argument as seen in table 2 above. |
Now, let’s walk through an example to demonstrate how these attributes and methods can be used.
Example 9: Manipulate date with datetime.date
from datetime import date def manipulate_date(): today = date.today() print("Today date is: {}, or for short: {}".format(today.ctime(), today.isoformat())) print("Today Year: {}, Month: {}, Day: {}".format(today.year, today.month, today.day)) print("We are in number {} week of this month".format(today.isoweekday())) print("Yesterday date was: {}".format(today.replace(day=today.day-1))) if __name__ == '__main__': manipulate_date()
Output
#2) Class datetime.time
This class represents the local time independent of the day. It holds only the time, and not the date associated with the time.
It takes in the optional arguments i.e. hour, minutes, second, microsecond and also the time zone information(tzinfo). While the tzinfo argument can be None or an instance of datetime.tzinfo(more on this later), the other Arguments if provided, must follow the following ranges, else ValueError will be raised;
0 <= hour < 24,
0 <= minute < 60,
0 <= second < 60,
0 <= microsecond < 1000000
The time class has many methods and attributes but the commonly used ones are,
The datetime.time Common Attributes and Methods
Attribute & Method | Description |
---|---|
time.min | The smallest representable time |
time.max | The largest representable time |
time.hour | Represents hour in range(24) |
time.minute | Represents minute in range(60) |
time.second | Represents second in range(60) |
time.microsecond | Represents microsecond in range(1000000) |
time.tzinfo | Represents the time zone |
time.fromisoformat(time_string) | Return a time object corresponding to a time_string as emitted by time.isoformat(). |
time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo) | Replace hour, minute, second, microsecond or tzinfo of a time object |
time.isoformat(timespec=’auto’) | Return a string representing the time in one of the formats here. It takes in an optional argument; timespec that specifies the number of additional components of the time to return. |
time.strftime() | Return a string representing the time following a format argument as seen in table 2 above. |
Now, let’s walk through an example to demonstrate how these attributes and methods can be used.
Example 10: Manipulate time with datetime.time
from datetime import time def manipulate_time(): made_time = time(hour=4, minute=23, second=3) print("Time: ", made_time.isoformat()) print("Hour: ", made_time.hour) print("Hour: ", made_time.minute) print("Hour: ", made_time.second) made_time2 = time.fromisoformat('12:34:56:123456') print('Time object: ', made_time2) print("Microsecond: ", made_time2.microsecond) print("HH:MM:SS :", made_time2.strftime('%H:%M:%S')) if __name__ == '__main__': manipulate_time()
Output
#3) Class datetime.datetime
This class combines information from both date and time objects. It can contain the attributes – year, month, day, hour, minute, second, microsecond, and tzinfo.
The datetime module has many methods, most of which we have seen above already. By using dir() as seen in example 4, on the datetime object we can obtain all the object’s valid methods.
Example 11: Obtain all attributes and methods of the datetime.datetime object.
from datetime import datetime for attr_meth in dir(datetime): if attr_meth.startswith('__'): # exclude properties that starts with '__' continue # differentiate methods from attributes if callable(getattr(datetime, attr_meth)): print(attr_meth+'()') else: print(attr_meth)
Output
Now, let’s walk through an example to demonstrate how most of these attributes and methods can be used.
Example 12: Manipulate date with datetime.datetime
from datetime import datetime def manipulate_datetime(): today_date = datetime.today() # same as datetime.now() custom_date = datetime(year=2021, month=5, day=23) # only date is set. today_timestamp = datetime.timestamp(today_date) # get today date time in timestamp print("Today Date: ", today_date) # same as today_date.isoformat() print("Today Timestamp: ", today_timestamp) print("Custom Date: ", custom_date) print("Year: {}, Month: {}, Day: {}".format(today_date.year, today_date.month, today_date.day)) print("From Timestamp: ", datetime.fromtimestamp(today_timestamp)) if __name__ == '__main__': manipulate_datetime()
Output
#4) datetime.timedelta
This class represents the difference between two dates, times, or datetimes. Subtracting dates produces a timedelta and adding or Subtracting timedelta from dates produces datetime.
Though the method .replace() exists, the best and easiest way to perform date manipulation is by using timedelta.
Example 13: Find datetime differences using timedelta.
from datetime import datetime, timedelta def manipulate_with_timedelta(): today_date = datetime.today() print("Today Date: ", today_date) date_3weeks_ago = today_date - timedelta(weeks=3) date_1yr_after = today_date + timedelta(days=365) print("Date 3 weeks ago: ", date_3weeks_ago) print("Date 1 year after: ", date_1yr_after) if __name__ == '__main__': manipulate_with_timedelta()
Output:
#5) Class datetime.tzinfo
Based on Wikipedia, time zones are defined as areas that observe a uniform standard time for legal, commercial, and social purposes. They are defined as offsets from UTC, ranging from UTC-12:00 to UTC+14:00. To know more about the time zones in general, visit the above-mentioned Wikipedia page.
In Python, the datetime.tzinfo holds a particular time zone information and it is an abstract base class. This means, it can’t be instantiated directly but can be passed to the constructors of datetime or time objects to reveal the timezone offset of local time from UTC.
NB: Timezone’s offset is the amount of hours the timezone is from UTC(Coordinated Universal Time).
Naive Vs Aware
Before we move forward, let’s understand what naive and aware are in time zones.
Naive datetime or time objects contain no timezone information, so they are “naive” to any sort of timezone and the tzinfo, in this case, is set or returns None.
Aware datetime or time objects on the other hand contain timezone information. In this case, a concrete subclass has to derive the tzinfo abstract class and implement its methods.
The tzinfo Abstract Base Class Methods
The tzinfo abstract base class has the following available methods that can be implemented;
a) utcoffset(self, dt)
This method returns the offset of local time from UTC in timedelta. Its return value is in the range:
-timedelta(hours=24) <= offset <= timedelta(hours=24)
Where if the offset is east of UTC, it is considered positive, and if the offset is west of UTC, it is considered negative.
It has a general implementation.
return CONSTANT # fixed-offset class return CONSTANT + self.dst(dt) # daylight-aware class
From above, we see that if utcoffset() does not return None, dst() should not return None either.
b) dst(self, dt)
Also known as Daylight Saving Time, it returns the daylight saving time adjustment as timedelta or None if DST information isn’t known.
It has the general implementation
def dst(self, dt): # a fixed-offset class: doesn't account for DST return timedelta(0)
or:
def dst(self, dt): # Code to set dston and dstoff to the time zone's DST # transition times based on the input dt.year, and expressed # in standard local time. if dston <= dt.replace(tzinfo=None) < dstoff: return timedelta(hours=1) else: return timedelta(0)
c) tzname(self, dt)
Return the time zone name as a string object. For example, “GMT”, “UTC”, “EDT”. If the string name isn’t known, it returns None.
Example 14: Identify timezone name
from datetime import datetime, timedelta from dateutil import tz def get_timezone_name(): # this date is naive naive = datetime.now() # get timezone and assign to naive date NYC = tz.gettz("America/New_York") aware_nyc = naive.astimezone(NYC) # get utc timezone and assign to naive date UTC = tz.tzutc() aware_utc = naive.astimezone(UTC) print("Naive timezone name: ", naive.tzname()) print("aware_utc timezone name: ", aware_utc.tzname()) print("aware_nyc timezone name: ", aware_nyc.tzname()) if __name__ == '__main__': get_timezone_name()
Output
Let’s put all these together in an example that shows how to inherit the tzinfo class and implement the methods described above.
Example 15: Complete example for tzinfo from datetime import datetime, tzinfo, timedelta.
from datetime import datetime, tzinfo, timedelta class TZ(tzinfo): def utcoffset(self, dt): return timedelta(hours=-4) def dst(self, dt): return timedelta(0) def tzname(self,dt): return "-04:00" def __repr__(self): return f"{self.__class__.__name__}()" aware = datetime(year=2021, month=5, day=23, tzinfo=TZ()) print(aware.isoformat()) # same as print(aware) print(aware.dst()) print(aware.tzname()) print(aware.strftime("%H:%M:%S %Z")) print('The {} is {:%H:%M}.'.format("time", aware))
Output
Frequently Asked Questions
Q #1) How do you combine date and time in Python?
Answer: The class datetime.datetime holds data for both time and date. However, we can create time and date separately and later combine them to produce a datetime using the datetime.datetime.combine() method.
Example 16: Combine date and time.
>>> import datetime >>> d = datetime.date(2021, 5, 26) # create date >>> t = datetime.time(4, 30) # create time >>> print("Date: ", d) Date: 2021-05-26 >>> print("Time: ", t) Time: 04:30:00 >>> combine = datetime.datetime.combine(d, t) # combine date and time >>> print("Date and Time: ", combine) Date and Time: 2021-05-26 04:30:00
Q #2) How do I get only the date in Python?
Answer: To get the current date in Python 3, we can use the built-in datetime module. In this module, there is a method datetime.date.today() that returns the current date. We can also get the date from a datetime object using the strftime() method with the right format string.
Example 17: Get the only date in Python
>>> import datetime >>> today_date1 = datetime.date.today() # get current date >>> print(today_date1) 2021-05-26 >>> today_datetime = datetime.datetime.now() # get current date and time >>> print(today_datetime) 2021-05-26 18:52:12.718775 >>> extract_date = today_datetime.strftime("%Y-%m-%d") # extract date >>> print(extract_date) 2021-05-26
Q #3) How do I get a timestamp?
Answer: In Python, we can get timestamps from a datetime object and vice versa. To get a timestamp from a datetime object, we use the datetime.timestamp() method and from timestamp to datetime object, we use the datetime.fromtimestamp() method.
Example 18: Timestamp Conversion
>>> from datetime import datetime >>> today = datetime.today() >>> today_timestamp = datetime.timestamp(today) >>> print(today_timestamp) 1622052117.603001 >>> today2 = datetime.fromtimestamp(today_timestamp) >>> print(today2) 2021-05-26 19:01:57.603001
Q #4) How do I get the current month in Python?
Answer: In Python, we can get the month number or name from a date or datetime object in many ways. We can use the object’s month attribute or we can use the strftime() method with the directives; “%m” or “%b”.
Example 19: Get current month from the date
>>> import datetime >>> d = datetime.date.today() # get today date >>> print(d) 2021-05-26 >>> d.month # get month as integer 5 >>> d.strftime('%m') # get month '05' >>> d.strftime('%b') # get month's name 'May'
More About Python DateTime
In Python, date, time, and DateTime are inbuilt classes that provide us with a number of inbuilt functions to deal with DateTime.
These functions are used to get the current date, time, and day.
Let’s see some of the examples for all the above.
Example 20:
from datetime import date def test_date(): today = date.today() print(“Today’s date is”, today) test_date()
Output:
Today’s date is 2018-09-29
Output:
Example 21:
from datetime import date def test_date(): today = date.today() #To print individual date componets print(“Date components are:”, today.day, today.month, today.year) test_date()
Output:
Date components are: 29 9 2018
Output:
Example 22:
from datetime import date def test_date(): today = date.today() #To print the weekday number(0=Monday , 6=Sunday) print(“Weekday number is:”, today.weekday()) test_date()
Output:
Weekday number is: 5
Output:
Example 23:
from datetime import datetime def test_date(): today = datetime.now() #Print the curren date and time print(“Current date and time is:”, today) test_date()
Output:
Current date and time is: 2018-09-29 21:26:09.578260
Output:
Example 24:
from datetime import datetime def test_date(): time = datetime.time(datetime.now()) #to retrieve the current time print(“Current time is:”, time) test_date()
Output:
Current time is: 21:28:32.980759
Output:
Formatting date and time using strftime() method
Example 25:
import datetime print(“Current date and time is:”, datetime.datetime.now()) print(“Current date and time using strftime method:”, datetime.datetime.now().strftime(“%y-%m-%d-%H-%M”) print(“Current year is:”, datetime.date.today().strftime(“%Y”)) print(“Month of year is:”, datetime.date.today().strftime(“%B”)) print(“Week number of the year is:”, datetime.date.today().strftime(“%W”)) print(“Weekday of the week is:”, datetime.date.today().strftime(“%w”)) print(“Day of the year is:”, datetime.date.today().strftime(“%j”)) print(“Day of the month is:”, datetime.date.today().strftime(“%d”)) print(“Day of the week is:”, datetime.date.today().strftime(“%A”))
Output:
Current date and time is: 2018-09-29 21:32:30.643372
Current date and time using the strftime method: 18-09-29-21-32
The current year is: 2018
Month of year is: September
Week number of the year is: 39
Weekday of the week is: 6
Day of the year is: 272
Day of the month is: 29
Day of the week is: Saturday
Output:
Conclusion
In this tutorial, we looked at Time and DateTime in Python. We found out that each of them is rich with methods that can help to manipulate the system clock.
Also, we closely examined what Epochs are and how they contribute to understanding how Python represents date.
=> Check Here For Simple Python Guide