Table of contents
1.
Introduction
2.
Python DateTime Module
2.1.
Python
3.
Python Date Class
3.1.
Python
3.2.
Python
3.3.
Python
4.
Python Time Class
4.1.
Python
4.2.
Python
4.3.
Python
5.
Python Datetime Class
5.1.
Python
5.2.
Python
6.
Python Timedelta Class
6.1.
Python
6.2.
Python
6.3.
Python
6.4.
Python
6.5.
Python
7.
Python DateTime.tzinfo()
7.1.
Python
7.2.
Python
8.
Python DateTime Timezone
8.1.
Python
8.2.
Python
8.3.
Python
8.4.
Python
9.
Frequently Asked Questions
9.1.
How can I get the current date & time in Python?
9.2.
How do I format a datetime object as a string?
9.3.
How can I perform arithmetic with date & time in Python?
10.
Conclusion
Last Updated: Jul 25, 2024
Easy

Date and Time in Python

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When working with date & time in your Python programs, it's important to know how to properly handle these values. Python provides a built-in module called "datetime" that makes it easy to work with date, time, & time intervals. 

Date and Time in Python

In this article, we'll cover the key classes & functions in the datetime module, including how to create date & time objects, perform arithmetic with them, format them as strings, & work with time zones.

Python DateTime Module

The datetime module in Python provides classes for working with date & time. Here are the main classes:

- date: Represents a date (year, month, day) 

- time: Represents a time (hour, minute, second, microsecond)

- datetime: Combines both a date & a time

- timedelta: Represents a duration or difference between two date or time


To use the datetime module, you first need to import it in your Python code:

import datetime


Once imported, you can create instances of the various classes & call methods on them. The datetime module provides a convenient way to handle common date/time operations.

For example, to get the current date & time, you can use the datetime.now() function:

  • Python

Python

current_dt = datetime.datetime.now()

print(current_dt) 
You can also try this code with Online Python Compiler
Run Code


Output

2023-07-03 14:30:45.123456


This creates a datetime object representing the current date & time, which you can then format, extract components from, or perform math on.

The datetime module is the foundation for working with date & time in Python. Its classes & functions make date/time handling straightforward.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass