Last Updated on March 20, 2023 by Prepbytes
The datetime module in Python is a built-in module that provides classes for working with dates and times. The datetime module defines several classes, including date, time, datetime, timedelta, and tzinfo, which allow you to work with dates and times in various ways.
Main Classes of the datetime Module
There are mainly 6 classes of datetime module present, which are listed below:
- date class: The date class is a part of the datetime module in Python, and represents a date (year, month, and day).
- time class: The time class is another class provided by the datetime module in Python, and represents a time of day (hours, minutes, seconds, and microseconds).
- datetime class: The datetime class is one of the most important classes provided by the datetime module in Python. It represents a combination of a date and a time and provides a range of methods to manipulate and work with date-time values.
- timedelta class: The timedelta class is another class provided by the datetime module in Python. It represents a duration of time (days, seconds, and microseconds) and can be used to perform arithmetic operations on date-time values.
- tzinfo class: The tzinfo class is a base class in the datetime module that can be used to define time zones for date-time objects. It is an abstract base class, which means that you cannot instantiate it directly, but you can subclass it to create your own time zone classes.
- timezone class: The timezone class is a subclass of tzinfo class in the datetime module that represents a fixed offset from UTC (Coordinated Universal Time). It is a simpler way to work with time zones compared to using a custom tzinfo class.
Date Class of datetime Module
Python uses the date class to create date objects. A date in the format YYYY-MM-DD is represented by an object of this class when it is instantiated. Year, Month and Date is required to construct date class.
Syntax of the date class:
datetime.date(year, month, day)
Let’s take an example of date class.
import datetime # Create a date object for January 1, 2023 d = datetime.date(2023, 1, 1) print(d) # Get the current date today = datetime.date.today() print(today) # Get the year, month, and day of a date object year = today.year month = today.month day = today.day print(year, month, day) # print each value separately # Format a date object as a string date_string = today.strftime("%d/%m/%Y") print(date_string) # Parse a date string into a date object date_string = "2023-03-15" parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d").date() print(parsed_date) # Get the day of the week as an integer (Monday is 0 and Sunday is 6) weekday = today.weekday() print(weekday)
Output:
2023-01-01
2023-03-15
2023 3 15
15/03/2023
2023-03-15
2
Time Class of datetime Module
The time class of the datetime module is used to display time of the day including hours, minutes, seconds, and microseconds.
Syntax of the time class:
datetime.time(hour, minute, second, microsecond, tzinfo, fold)
Let’s take an example of time class.
import datetime # Create a time object for 9:30 AM t = datetime.time(9, 30) print(t) # Get the current time now = datetime.datetime.now() current_time = now.time() print(current_time) # Get the hour, minute, and second of a time object hour = t.hour minute = t.minute second = t.second print(hour, minute, second) # print each value separately # Format a time object as a string time_string = t.strftime("%I:%M %p") print(time_string) # Compare two time objects time1 = datetime.time(8, 30) time2 = datetime.time(9, 30) if time1 < time2: print("time1 is earlier than time2") else: print("time1 is late than time2")
Output:
09:30:00
08:18:22.140074
9 30 0
09:30 AM
time1 is earlier than time2
Datetime Class of datetime Module
The datetime class is the combination of the above two classes a date and a time. The datetime class also provides a range of methods to manipulate and work with date-time values.
Syntax of the datetime class:
datetime.datetime(year, month, day, hour, minute, second, microsecond, tzinfo, fold)
Let’s take an example of the datetime class.
import datetime # Create a datetime object for January 1, 2023 at 9:30 AM dt = datetime.datetime(2023, 1, 1, 9, 30) print(dt) # 2023-01-01 09:30:00 # Get the current datetime now = datetime.datetime.now() print(now) # current datetime in the format yyyy-mm-dd hh:mm:ss.microseconds # Get the year, month, day, hour, minute, and second of a datetime object year = now.year month = now.month day = now.day hour = now.hour minute = now.minute second = now.second print(year, month, day, hour, minute, second) # print each value separately # Format a datetime object as a string datetime_string = now.strftime("%Y-%m-%d %H:%M:%S") print(datetime_string) # formatted datetime string # Parse a datetime string into a datetime object datetime_string = "2023-03-15 14:30:00" parsed_datetime = datetime.datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S") print(parsed_datetime) # 2023-03-15 14:30:00 # Create a timedelta object representing a duration of time delta = datetime.timedelta(days=7) new_date = now + delta print(new_date) # current date + 7 days # Get the difference between two datetime objects dt1 = datetime.datetime(2022, 1, 1, 9, 30) dt2 = datetime.datetime(2023, 1, 1, 9, 30) delta = dt2 - dt1 print(delta.days) # number of days between the two datetime objects
Output:
2023-01-01 09:30:00
2023-03-15 08:33:49.745378
2023 3 15 8 33 49
2023-03-15 08:33:49
2023-03-15 14:30:00
2023-03-22 08:33:49.745378
365
Timedelta Class of the datetime Module
Python’s timedelta class is used to determine when two dates are different and can also be used to manipulate dates. The timedelta class can also be used to perform arithmetic operations on date-time values.
Syntax of the timedelta class:
datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
Let’s see an example of the timedelta class.
import datetime # Create a timedelta object representing a duration of time delta = datetime.timedelta(days=7, hours=2, minutes=30) print(delta) # Add a timedelta to a datetime object dt = datetime.datetime(2023, 3, 15, 14, 30) new_dt = dt + delta print(new_dt) # Subtract a timedelta from a datetime object dt = datetime.datetime(2023, 3, 15, 14, 30) new_dt = dt - delta print(new_dt) # Create a timedelta from the difference between two datetime objects dt1 = datetime.datetime(2023, 3, 8, 12, 0) dt2 = datetime.datetime(2023, 3, 15, 14, 30) delta = dt2 - dt1 print(delta) # Convert a timedelta to seconds delta = datetime.timedelta(hours=2, minutes=30) total_seconds = delta.total_seconds() print(total_seconds)
Output:
7 days, 2:30:00
2023-03-22 17:00:00
2023-03-08 12:00:00
7 days, 2:30:00
9000.0
Tzinfo Class of the datetime Module
The tzinfo class of the datetime module is used to define the time zones for the datetime modules.
Let’s take an example of the tzinfo class.
import datetime class EST(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(hours=-5) def dst(self, dt): return datetime.timedelta(0) def tzname(self, dt): return "EST" # Create a datetime object in the EST time zone dt = datetime.datetime(2023, 3, 15, 14, 30, tzinfo=EST()) print(dt) # Get the current time in the EST time zone now = datetime.datetime.now(tz=EST()) print(now) # Convert a datetime object to a different time zone dt = datetime.datetime(2023, 3, 15, 14, 30, tzinfo=EST()) utc_dt = dt.astimezone(datetime.timezone.utc) print(utc_dt)
Output:
2023-03-15 14:30:00-05:00
2023-03-15 03:54:58.600322-05:00
2023-03-15 19:30:00+00:00
Timezone class of the datetime module:
When displaying time according to a particular region’s timezone, DateTime’s timezones feature can be used. It is a simpler way to work with time zones compared to using a custom tzinfo class.
Let’s take an example of the timezone class.
import datetime # Create a timezone object representing Pacific Standard Time (UTC-8) pst = datetime.timezone(datetime.timedelta(hours=-8)) # Create a datetime object with the current date and time in the Pacific time zone now = datetime.datetime.now(tz=pst) print(now) # Convert a datetime object to a different time zone utc_now = now.astimezone(datetime.timezone.utc) print(utc_now)
Output:
2023-03-15 01:01:03.168324-08:00
2023-03-15 09:01:03.168324+00:00
Conclusion
In conclusion, this article will help you to understand the datetime module of the Python. In addition, you will also learn about import classes of the datetime module with help of an example.
FAQs of the datetime module
1. How do I convert a string to a datetime object in Python?
You can use the strptime() method of the datetime class to parse a string and convert it to a datetime object. This method takes a format string that specifies the format of the input string. For example, to convert the string "2023-03-15 14:30:00" to a datetime object, you can use the format string "%Y-%m-%d %H:%M:%S".
2. How do I get the current date and time in Python?
You can use the datetime.now() method to get the current date and time as a datetime object. By default, this method returns the current date and time in the local timezone. You can also pass a timezone object to this method to get the current date and time in a specific timezone.
3. How do I compare datetime objects in Python?
You can use the comparison operators (<, <=, >, >=, ==, and !=) to compare datetime objects. When you compare two datetime objects, Python compares them based on their point in time. For example, datetime(2023, 3, 15) < datetime(2023, 3, 16) will return True.
4. How do I calculate the difference between two datetime objects in Python?
You can subtract one datetime object from another to get a timedelta object representing the difference between them. For example, to get the difference between two datetime objects datetime1 and datetime2, you can use the expression datetime2 – datetime1.
5. How do I convert a datetime object to a Unix timestamp in Python?
You can use the timestamp() method of a datetime object to convert it to a Unix timestamp, which is the number of seconds since January 1, 1970, 00:00:00 UTC. For example, to convert a datetime object datetime_obj to a Unix timestamp, you can use the expression datetime_obj.timestamp().