Python Date Class
The date class in the datetime module represents a date (year, month, day) without any time information. You can create a date object by calling the date() constructor & passing in the year, month, & day as integers:
Python
my_date = datetime.date(2023, 7, 4)
print(my_date)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-04
You can access the individual components of a date using the year, month, & day attributes:
Python
print(my_date.year)
print(my_date.month)
print(my_date.day)

You can also try this code with Online Python Compiler
Run Code
Output
2023
7
4
The date class also provides some useful class methods:
- date.today(): Returns the current local date
- date.fromtimestamp(timestamp): Creates a date object from a POSIX timestamp (seconds since epoch)
- date.fromisoformat(date_string): Creates a date object from an ISO-formatted date string (YYYY-MM-DD)
For example :
Python
today = datetime.date.today()
print(today)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-03
You can compare two date objects using comparison operators like ==, !=, <, <=, >, >=. This allows you to check if one date is before, after, or equal to another.
The date class makes it easy to work with date separately from time in Python. Its methods & attributes provide convenient ways to create, access, & compare date objects.
Python Time Class
The time class in the datetime module represents a time of day, independent of any particular date. You can create a time object by calling the time() constructor & passing in the hour, minute, second, & microsecond as integers:
Python
my_time = datetime.time(14, 30, 45, 123456)
print(my_time)

You can also try this code with Online Python Compiler
Run Code
Output:
14:30:45.123456
The hour, minute, & second arguments are required, while microsecond is optional (defaults to 0 if not provided).
You can access the individual components of a time using the hour, minute, second, & microsecond attributes:
Python
print(my_time.hour)
print(my_time.minute)
print(my_time.second)
print(my_time.microsecond)

You can also try this code with Online Python Compiler
Run Code
Output
14
30
45
123456
The time class also provides a few useful methods:
- time.replace(hour=, minute=, second=, microsecond=): Creates a new time object with the specified fields replaced
- time.isoformat(timespec='auto'): Returns a string representing the time in ISO 8601 format (HH:MM:SS.ffffff)
For example :
Python
new_time = my_time.replace(hour=10, second=0)
print(new_time)

You can also try this code with Online Python Compiler
Run Code
Output
10:30:00.123456
Unlike the date class, the time class does not have comparison methods. To compare two time objects, you can compare their individual components.
The time class is useful when you need to store or manipulate time values separate from date, Its attributes & methods allow you to easily work with time in your Python code.
Python Datetime Class
The datetime class in the datetime module combines both a date & a time into a single object. You can create a datetime object by calling the datetime() constructor & passing in the year, month, day, hour, minute, second, & microsecond as integers:
my_datetime = datetime.datetime(2023, 7, 4, 14, 30, 45, 123456)
print(my_datetime)
Output:
2023-07-04 14:30:45.123456
The year, month, & day arguments are required, while hour, minute, second, & microsecond are optional (they default to 0 if not provided).
You can access the individual components of a datetime using attributes like year, month, day, hour, minute, second, & microsecond:
Python
print(my_datetime.year)
print(my_datetime.month)
print(my_datetime.day)
print(my_datetime.hour)
print(my_datetime.minute)
print(my_datetime.second)
print(my_datetime.microsecond)

You can also try this code with Online Python Compiler
Run Code
Output
2023
7
4
14
30
45
123456
The datetime class provides several useful methods, which are:
- datetime.today(): Returns the current local datetime
- datetime.now(tz=None): Returns the current local datetime, with optional time zone info
- datetime.fromtimestamp(timestamp, tz=None): Creates a datetime from a POSIX timestamp, with optional time zone info
- datetime.strptime(date_string, format): Creates a datetime from a string & corresponding format code
- datetime.strftime(format): Formats a datetime as a string based on a given format code
For example :
Python
formatted_dt = my_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_dt)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-04 14:30:45
You can compare two datetime objects using the same comparison operators as the date class (<, <=, >, >=, ==, !=). This allows you to determine the order or equality of two datetime instances.
The datetime class is commonly used when you need to store or work with complete timestamps. Its wide range of methods gives you a lot of flexibility in creating, manipulating, & formatting datetime objects in Python.
Python Timedelta Class
The timedelta class in the datetime module represents a duration or the difference between two date or time. You can create a timedelta object by specifying the number of days, seconds, & microseconds:
Python
my_timedelta = datetime.timedelta(days=7, seconds=3600, microseconds=1000)
print(my_timedelta)

You can also try this code with Online Python Compiler
Run Code
Output:
7 days, 1:00:00.001000
You can access the individual components of a timedelta using the days, seconds, & microseconds attributes:
Python
print(my_timedelta.days)
print(my_timedelta.seconds)
print(my_timedelta.microseconds)

You can also try this code with Online Python Compiler
Run Code
Output
7
3600
1000
The total number of seconds in a timedelta can be obtained using the total_seconds() method:
Python
total_secs = my_timedelta.total_seconds()
print(total_secs)

You can also try this code with Online Python Compiler
Run Code
Output:
694800.001
You can perform arithmetic operations with timedelta objects, such as addition, subtraction, & multiplication:
Python
td1 = datetime.timedelta(days=2)
td2 = datetime.timedelta(hours=12)
td_sum = td1 + td2
print(td_sum)

You can also try this code with Online Python Compiler
Run Code
Output
2 days, 12:00:00
Timedelta objects are commonly used to add or subtract time from datetime objects:
Python
current_dt = datetime.datetime.now()
one_week_later = current_dt + datetime.timedelta(weeks=1)
print(one_week_later)

You can also try this code with Online Python Compiler
Run Code
Output:
2023-07-10 14:45:30.123456
The timedelta class is a convenient way to represent & manipulate time durations in Python. Its attributes & methods make it easy to perform time-based calculations & comparisons.
Python DateTime.tzinfo()
The tzinfo() class in the datetime module provides a way to represent time zones. It is an abstract base class, meaning you can't create instances of it directly. Instead, you need to define a subclass that implements the required methods.
The most important methods to implement in a tzinfo subclass are:
- utcoffset(dt): Returns the offset from UTC in minutes east of UTC, as a timedelta object
- dst(dt): Returns the daylight saving time (DST) adjustment, as a timedelta object
- tzname(dt): Returns the time zone name as a string
Let’s look at s simple example of a custom tzinfo subclass that represents a fixed offset from UTC:
class FixedOffset(datetime.tzinfo):
def __init__(self, offset):
self.offset = datetime.timedelta(minutes=offset)
def utcoffset(self, dt):
return self.offset
def dst(self, dt):
return datetime.timedelta(0)
def tzname(self, dt):
return f"UTC{self.offset}"
You can use this custom tzinfo subclass to create timezone-aware datetime objects:
Python
my_tz = FixedOffset(-300) # UTC-5
my_dt = datetime.datetime(2023, 7, 4, 14, 30, tzinfo=my_tz)
print(my_dt)

You can also try this code with Online Python Compiler
Run Code
Output:
2023-07-04 14:30:00-05:00
Python also provides the pytz module, which is a popular third-party library for working with time zones. It contains a comprehensive database of time zone information & implements the tzinfo interface.
For example :
Python
import pytz
ny_tz = pytz.timezone("America/New_York")
ny_dt = ny_tz.localize(datetime.datetime(2023, 7, 4, 14, 30))
print(ny_dt)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-04 14:30:00-04:00
The tzinfo class & its subclasses allow you to work with time zones in Python. By creating timezone-aware datetime objects, you can perform accurate time calculations & conversions across different time zones.
Python DateTime Timezone
In Python, you can work with time zones using the datetime module in combination with the pytz library. The pytz library provides a comprehensive database of time zone information & makes it easy to create timezone-aware datetime objects.
To use pytz, you first need to install it:
pip install pytz
Once installed, you can create a timezone-aware datetime using the localize() method provided by pytz:
Python
import pytz
from datetime import datetime
ny_tz = pytz.timezone("America/New_York")
ny_dt = ny_tz.localize(datetime(2023, 7, 4, 14, 30))
print(ny_dt)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-04 14:30:00-04:00
You can convert a timezone-aware datetime to a different time zone using the astimezone() method:
Python
la_tz = pytz.timezone("America/Los_Angeles")
la_dt = ny_dt.astimezone(la_tz)
print(la_dt)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-04 11:30:00-07:00
To get the current datetime in a specific time zone, you can use the now() method provided by the time zone object:
Python
current_ny_dt = ny_tz.now()
print(current_ny_dt)

You can also try this code with Online Python Compiler
Run Code
Output:
2023-07-03 15:45:30.123456-04:00
When working with time zones, it's important to be aware of daylight saving time (DST) transitions. The pytz library automatically handles DST transitions based on the historical & future DST information in its database.
You can also work with UTC (Coordinated Universal Time) using pytz:
Python
utc_dt = datetime.now(pytz.UTC)
print(utc_dt)

You can also try this code with Online Python Compiler
Run Code
Output
2023-07-03 19:45:30.123456+00:00
Working with time zones can be complex due to the various rules & transitions across different regions. However, the pytz library simplifies the process by providing an accurate & up-to-date time zone database, making it easier to handle time zone conversions & calculations in your Python code.
Frequently Asked Questions
How can I get the current date & time in Python?
You can use the datetime.now() function from the datetime module to get the current date & time.
How do I format a datetime object as a string?
Use the strftime() method of a datetime object & provide a format string to specify the desired output format.
How can I perform arithmetic with date & time in Python?
You can use timedelta objects to represent durations & perform addition or subtraction with datetime objects.
Conclusion
In this article, we've learned about the datetime module in Python & its key classes for working with date, time, & time intervals. We covered the date, time, datetime, & timedelta classes, along with their main methods & attributes. We also discussed how to work with time zones using the pytz library.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.