In this tutorial, we’ll cover the concept of datetime format in Python and explain using examples. The datatime is a built-in module in Python, which also provides a class with the same name. We’ll explain the usage of the datetime class. So, you will learn about the date-time formatting from different points of view. Like, how to get the date time in Python and represent it in a human-readable format.
In Python, the datetime format is not just getting and displaying the date and time. It also reflects the ability to set up and show different time zones. The other things are like showing a date-time string in the local native style. You can do basic operations like finding the difference between two dates, parsing a date string, etc.
How to Format DateTime in Python With Examples
As stated earlier, the Python datetime
module comes with a class with the same name. It provides simple methods that we can use to represent and process date-time. The below code is one of the simplest examples.
from datetime import datetime
# Get the current date and time
current_datetime = datetime.now()
print("Current Datetime:", current_datetime)
Also Read: Python Datetime Explained with Examples
The strftime
is a simple function of the datetime class. Let’s learn how to use it to format a date string.
DateTime Format Using Python strftime
The strftime
method is the key to formatting datetime
objects into human-readable strings. It stands for “string format time” and takes a format string as an argument.
# Example 1: Basic strftime formatting
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Datetime:", formatted_datetime)
Output:
Formatted Datetime: 2023-12-24 15:30:45
In the format string:
%Y
represents the year with a century as a decimal number.%m
represents the month as a zero-padded decimal number.%d
represents the day of the month as a zero-padded decimal number.%H
represents the hour (00 to 23).%M
represents the minute (00 to 59).%S
represents the second (00 to 59).
Using strftime
to Format Date
When you only need to display the date without the time, you can customize the format accordingly.
# Example 2: Custom date formatting
custom_date_format = current_datetime.strftime("%A, %B %d, %Y")
print("Custom Date Format:", custom_date_format)
Output:
Custom Date Format: Saturday, December 24, 2023
In the format string:
%A
represents the full weekday name.%B
represents the full month’s name.
Check Out: Python Time Functions Explained
Using strftime
to Format Time
Similarly, we can target the time component and customize the format accordingly.
# Example 3: Custom time formatting
custom_time_format = current_datetime.strftime("%I:%M %p")
print("Custom Time Format:", custom_time_format)
Output:
Custom Time Format: 03:30 PM
In the format string:
%I
represents the hour (12-hour clock).%M
represents the minute.%p
represents either AM or PM.
Mixed DateTime Format in Python
For combined date and time formatting, merge the elements from the previous examples.
# Example 4: Custom date and time formatting
custom_datetime_format = current_datetime.strftime("%A, %B %d, %Y %I:%M %p")
print("Custom Datetime Format:", custom_datetime_format)
Output:
Custom Datetime Format: Saturday, December 24, 2023 03:30 PM
Localize Date-time Using pytz
Module
To localize the datetime format, we can use Python’s PYTZ library. It lets us play with time zones in a date-time string.
Installing pytz
Before using pytz
, you need to install it:
pip install pytz
Python Example to Apply Timezone
from datetime import datetime
import pytz
# Create a datetime object with timezone information
dt_with_timezone = datetime.now(pytz.timezone('America/New_York'))
print("Datetime with Timezone:", dt_with_timezone)
# Format the datetime with timezone
formatted_dt_timezone = dt_with_timezone.strftime("%Y-%m-%d %H:%M:%S %Z")
print("Formatted Datetime with Timezone:", formatted_dt_timezone)
Output:
Datetime with Timezone: 2023-12-24 15:30:45.678901-05:00
Formatted Datetime with Timezone: 2023-12-24 15:30:45 EST
In the format string:
%Z
represents the timezone name.
Parse Datetime Strings
At times we need to parse a date string. To achieve this, we need to convert the date string into datetime
. Let’s quickly use the method strptime
for this purpose.
from datetime import datetime
# Example 5: Parsing datetime string
date_string = "2023-12-24 15:30:45"
parsed_datetime = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed Datetime:", parsed_datetime)
Output:
Parsed Datetime: 2023-12-24 15:30:45
The format string in strptime
should match the structure of the input string.
Time Difference Between the Dates
The first thing is to convert the dates using datetime. After that, we can measure the time difference between these objects. It is useful in various applications, such as measuring elapsed time or scheduling tasks.
from datetime import datetime, timedelta
# Example 6: Time difference between datetimes
start_time = datetime(2023, 12, 24, 10, 30, 0)
end_time = datetime(2023, 12, 24, 15, 45, 30)
time_difference = end_time - start_time
print("Time Difference:", time_difference)
Output:
Time Difference: 5:15:30
The result is a time delta object representing the difference between two datetime objects. You can format the same to make it human-readable.
# Example 7: Formatting time difference
formatted_time_difference = str(time_difference)
print("Formatted Time Difference:", formatted_time_difference)
Output:
Formatted Time Difference: 5:15:30
Handle Time Zones with timedelta
When working with time differences, especially across time zones, consider using the pytz
library for accurate calculations.
from datetime import datetime, timedelta
import pytz
# Example 8: Handling time zones in timedelta
start_time_utc = datetime(2023, 12, 24, 10, 30, 0, tzinfo=pytz.utc)
end_time_utc = datetime(2023, 12, 24, 15, 45, 30, tzinfo=pytz.utc)
time_difference_utc = end_time_utc - start_time_utc
print("Time Difference (UTC):", time_difference_utc)
Output:
Time Difference (UTC): 5:15:30
Common Date and Time Formats
Understanding common date and time formats becomes necessary when working with data interchange or database storage.
The ISO 8601 Format
ISO 8601 is an international standard for representing dates and times.
# Example 9: Formatting in ISO 8601 format
iso_format = current_datetime.isoformat()
print("ISO 8601 Format:", iso_format)
Output:
ISO 8601 Format: 2023-12-24T15:30:45.678901
The RFC 3339 Format
RFC 3339 is another format commonly used for date and time representation.
# Example 10: Formatting in RFC 3339 format
rfc3339_format = current_datetime.strftime("%Y-%m-%dT%H:%M:%S%z")
print("RFC 3339 Format:", rfc3339_format)
Output:
RFC 3339 Format: 2023-12-24T15:30:45+0000
Summary – DateTime Format in Python
In this comprehensive guide, you explored the datetime format in Python from various aspects. You learned strftime
and used it to format date and time, localize, and parse datetime strings. You also learned to deal with time differences and understand common date and time formats.
The tutorial also mentioned how to handle time zones which is useful when you work with applications in multiple regions. Utilize the pytz
library for accurate timezone support, and always handle errors gracefully when parsing datetime strings. This ability to work with dates and times effectively is a valuable skill for any Python developer. We hope this guide gave you all the tools to manage date-time effectively in Python.
Happy Coding!