You are currently viewing Handling Date & Time in Python

Handling Dates & Time in Python is an essential part while working on simple or complex projects. Python Programming provides a variety of built-in and third-party libraries that make it easy to work with dates and time. In this article, We will learn about date and time handling.

Advertisements

To learn Python programming basics & advanced concepts refer to Python Tutorial with Examples.

We will learn the basics of creating and converting datetime objects, different formats for date and time, working with timezones, common datetime functions, and operations that can be performed on dates and time.

1. Date and Time Handling in Python

Date and time are fundamental concepts in many programming applications. In Python, date and time data can be stored and manipulated using a variety of objects and data types. The most commonly used object for handling date and time is the datetime object, which is part of the built-in datetime module.

The datetime object represents a specific date and time and provides a range of methods for working with the dates. It also makes it easier to perform calculations and comparisons with date and time data.

Storing date and time as a datetime object rather than a string is important because it provides us with a standardized format for handling and manipulating.

1.1 Creating a datetime Object

The datetime() constructor is used to create a new datetime object. It takes in various parameters that allow you to specify the date and time components while creating a new object.

The basic syntax for creating a datetime object:


# Syntax of datetime()
datetime(year, month, day, hour, minute, second, microsecond, tzinfo)

Though this method can be used to create datetime object, we can also use the datetime.now() function to get the current system data and time:


# Creating datetime object 
# Holding current date and time

# Import datetime
from datetime import datetime

# Create the datetime Object
current_datetime = datetime.now()
print(current_datetime)

# Output:
# 2023-03-16 20:37:56.876245

1.2 datetime Objects From String

To convert datetime strings into datetime objects use the datetime.strptime() function. The strptime() function takes two arguments: the datetime string to parse and the format string that specifies the format of the datetime string.


# Program that convert String Date to datetime object

# Import
from datetime import datetime

# String should be proper Date
date_string = '2022-03-17'

# Format for the date
date_format = '%Y-%m-%d'
datetime_object = datetime.strptime(date_string, date_format)

print(datetime_object)

# Output:
# 2022-03-17 00:00:00

You can also create datetime objects from strings that include both dates and time.


# Datetime object from String with time
from datetime import datetime

datetime_string = '2022-03-17 12:34:56'
datetime_format = '%Y-%m-%d %H:%M:%S'

Convert data & time string to datetime object
datetime_object = datetime.strptime(datetime_string, datetime_format)

print(datetime_object)

2. Different formats for Date and time

Working with dates and time in Python involves working with a variety of formats. Some of the most commonly used formats include ISO 8601, RFC 2822, and custom format strings.

2.1 ISO 8601 format

The basic format for dates in ISO 8601 is YYYY-MM-DD, while the basic format for time is HH:MM:SS. The basic format for datetime strings is YYYY-MM-DDTHH:MM:SS, where T is the separator between the date and time components.

ISO 8601 is an international standard that specifies the format for representing dates, time, and datetime strings.


# Import
from datetime import datetime

# ISO 8601 format
date_string = '2022-03-17T12:34:56'
date_format = '%Y-%m-%dT%H:%M:%S'
datetime_object = datetime.strptime(date_string, date_format)
print(datetime_object)

# Output:
# 2022-03-17 12:34:56

2.2 RFC 2822 format

The format for dates in RFC is DD Mon YYYY, where DD is the day of the month, Mon is the abbreviated name of the month, and YYYY is the four-digit year. The format for time is HH:MM:SS, followed by the time zone offset in the format +/-HHMM.


# RFC 2822 format
date_string = 'Thu, 17 Mar 2022 12:34:56 +0800'
date_format = '%a, %d %b %Y %H:%M:%S %z'
datetime_object = datetime.strptime(date_string, date_format)
print(datetime_object)

2.3 Custom format strings

Python also allows for custom format strings to be used to parse and format datetime strings. Some commonly used format codes include %Y for the year, %m for the month, %d for the day, %H for the hour, %M for the minute, and %S for the second.


# Custom format string
date_string = '2022-03-17 12:34:56'
date_format = '%Y-%m-%d %H:%M:%S'
datetime_object = datetime.strptime(date_string, date_format)
print(datetime_object)

I hope you are clear now on how to work with time zones while using data & time in Python

3. Working with Timezones

Timezones are regions of the world that share the same standard time. Each timezone is identified by a name and a UTC offset, which represents the difference in hours and minutes between the timezone’s standard time and Coordinated Universal Time (UTC).

3.1 timezone-aware datetime

A timezone-aware datetime is a datetime object that includes information about its timezone. This means that the datetime object has been associated with a specific timezone, so that you can convert it to other timezones and perform arithmetic operations on it without losing track of the timezone information.

To create a timezone-aware datetime object in Python, you can use the pytz library along with the datetime module.


# Import
import datetime
import pytz

# Create a datetime object representing 2022-01-01 12:00:00
dt = datetime.datetime(2022, 1, 1, 12, 0, 0)

# Create a timezone object for US/Eastern
eastern_tz = pytz.timezone('US/Eastern')

# Make the datetime object timezone-aware
dt_eastern = eastern_tz.localize(dt)

print(dt_eastern)

# Output:
# 2022-01-01 12:00:00-05:00

3.2 convert between timezones

Once we have a timezone-aware datetime object, we can convert it to other timezones using the astimezone() method.


# Create a timezone object for UTC
utc_tz = pytz.timezone('UTC')

# Convert the datetime object to UTC
dt_utc = dt_eastern.astimezone(utc_tz)

print(dt_utc)

# Output:
# 2022-01-01 17:00:00+00:00

You can also convert datetime objects between other timezones by passing in a different timezone object to the astimezone() method.


# Create a timezone object for Australia/Sydney
sydney_tz = pytz.timezone('Australia/Sydney')

# Convert the datetime object to Australia/Sydney
dt_sydney = dt_eastern.astimezone(sydney_tz)

print(dt_sydney)

# Output:
# 2022-01-02 04:00:00+11:00

4. datetime Functions

Python’s datetime module provides a number of functions for working with datetime objects. Here are some of the most commonly used functions:

date()Returns the date object of the datetime
time()Returns the time object of the datetime
strftime(format)Returns a string representation of the datetime object, based on the format string passed
strptime(date_string, format)Parses a string representing a datetime and returns a datetime object
timedelta()Represents a duration, the difference between two dates or times
Basic functions of datetime module

5. Operations on Date and Time in Python

One of the benefits of using the Python datetime module for processing date and time is that you can do a lot of operations on it. You can add days to dates, subtract, or compare them. For now, we will see how we can add and subtract two dates from each other.

5.1 Add Days to Date and Time

To add days or time to a datetime object in Python, you can use the timedelta() function from the datetime module. The timedelta() function represents a duration or difference between two dates or times.


import datetime

# Get the current datetime
dt = datetime.datetime.now() 

# Create a timedelta object representing one day
one_day = datetime.timedelta(days=1) 
 
# Add the timedelta to the datetime to get tomorrow's date
dt_tomorrow = dt + one_day 
print(dt_tomorrow)

You can also use timedelta() to add hours, minutes, seconds, and microseconds to a datetime object. Here’s an example of how to add 2 hours and 30 minutes to a datetime object:


import datetime

# Get the current datetime
dt = datetime.datetime.now() 

# Create a timedelta object representing 2 hours 30 mins
two_hours_thirty_mins = datetime.timedelta(hours=2, minutes=30) 

# Add the timedelta to the datetime
dt_plus_2h30m = dt + two_hours_thirty_mins  
print(dt_plus_2h30m)

5.2 Difference Between Two Dates

To find the difference between two dates in Python, you can subtract one datetime object from another. The resulting object will be a timedelta object representing the duration between the two dates.


import datetime

# Create a datetime object representing the first date
date1 = datetime.date(2022, 3, 10) 

# Create a datetime object representing the second date
date2 = datetime.date(2022, 3, 15)  

# Subtract the first date from the second date to get the duration
diff = date2 - date1 
 
# Print the number of days in the duration
print(diff.days)  

6. Summary and Conclusion

In this article, we have learned how to handle date and time in Python by using Datetime object and other methods. We have covered creating datetime objects, using different formats of date and time, converting string to date etc. I hope this article was helpful, if you have any questions, please leave them in the comment section.

Happy Coding!

Related Article